本文整理汇总了C#中System.Type.GetGenericArguments方法的典型用法代码示例。如果您正苦于以下问题:C# Type.GetGenericArguments方法的具体用法?C# Type.GetGenericArguments怎么用?C# Type.GetGenericArguments使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Type
的用法示例。
在下文中一共展示了Type.GetGenericArguments方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: InferType
public static IType InferType(Type type, IMetadataContainer container)
{
Type genericTypeDefinition = type.GetGenericArguments().Any() ? type.GetGenericTypeDefinition() : type;
if (typeof(IFunction<,>).IsAssignableFrom(genericTypeDefinition))
{
Type left = type.GetGenericArguments()[0];
Type right = type.GetGenericArguments()[1];
return new Types.ArrowType(InferType(left, container), InferType(right, container));
}
else if (typeof(Either<,>).IsAssignableFrom(genericTypeDefinition))
{
Type left = type.GetGenericArguments()[0];
Type right = type.GetGenericArguments()[1];
return new Types.SumType(InferType(left, container), InferType(right, container));
}
else if (typeof(Tuple<,>).IsAssignableFrom(genericTypeDefinition))
{
Type left = type.GetGenericArguments()[0];
Type right = type.GetGenericArguments()[1];
return new Types.ProductType(InferType(left, container), InferType(right, container));
}
else if (type.IsGenericParameter)
{
return new Types.TypeParameter(type.Name);
}
else
{
container.ResolveType(type.Name);
var genericParameters = type.GetGenericArguments().Select(t => InferType(t, container)).ToArray();
return new Types.TypeSynonym(type.Name, genericParameters);
}
}
示例2: Populate
public object Populate(string propertyName, Type propertyType, object currentValue, int depth, Func<int, string, Type, object, PropertyInfo, object> populateKey, Func<int, string, Type, object, PropertyInfo, object> populateValue)
{
if (currentValue != null && ((IDictionary)currentValue).Count > 0)
{
return currentValue;
}
IDictionary newDictionary;
if (currentValue != null && ((IDictionary)currentValue).Count == 0)
{
newDictionary = (IDictionary)currentValue;
}
else
{
newDictionary = (IDictionary)Activator.CreateInstance(propertyType);
}
for (var i = 0; i < AutoBuilderConfiguration.DefaultCollectionItemCount; i++)
{
newDictionary.Add(populateKey(depth + 1, propertyName, propertyType.GetGenericArguments()[0], null, null), populateValue(depth + 1, propertyName, propertyType.GetGenericArguments()[1], null, null));
}
return newDictionary;
}
示例3: DictionaryJsonSerializer
private DictionaryJsonSerializer(Type type, bool encrypt, JsonMappings mappings, bool shouldUseAttributeDefinedInInterface)
{
_encrypt = encrypt;
_mappings = mappings;
_shouldUseAttributeDefinedInInterface = shouldUseAttributeDefinedInInterface;
Type keyType;
if (type.IsAssignableToGenericIDictionary())
{
var genericArguments = type.GetGenericArguments();
keyType = genericArguments[0];
if (typeof(IDictionary<string, object>).IsAssignableFrom(type))
{
_valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
_write = GetIDictionaryOfStringToObjectWriteAction();
}
else if (type.IsAssignableToGenericIDictionaryOfStringToAnything())
{
_valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
_write = GetIDictionaryOfStringToAnythingWriteAction();
}
else
{
_keySerializer = JsonSerializerFactory.GetSerializer(genericArguments[0], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
_valueSerializer = JsonSerializerFactory.GetSerializer(genericArguments[1], _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
_write = GetIDictionaryOfAnythingToAnythingWriteAction();
}
}
else
{
keyType = typeof(object);
_keySerializer = JsonSerializerFactory.GetSerializer(typeof(object), _encrypt, _mappings, shouldUseAttributeDefinedInInterface);
_valueSerializer = _keySerializer;
_write = GetIDictionaryOfAnythingToAnythingWriteAction();
}
if (type.IsInterface)
{
if (type.IsGenericIDictionary())
{
type = typeof(Dictionary<,>).MakeGenericType(
type.GetGenericArguments()[0], type.GetGenericArguments()[1]);
}
else if (type == typeof(IDictionary))
{
type = typeof(Dictionary<object, object>);
}
else
{
throw new NotSupportedException(type.FullName);
}
}
_createDictionary = GetCreateDictionaryFunc(type);
_deserializeKey = GetDeserializeKeyFunc(keyType);
_addToDictionary = GetAddToDictionaryAction(type);
}
示例4: CanParseType
public virtual bool CanParseType(Type type)
{
return
type.IsKeyValuePairType() &&
StringParsing.GetParser(type.GetGenericArguments()[0]) != null &&
StringParsing.GetParser(type.GetGenericArguments()[1]) != null;
}
示例5: GetFullName
public static string GetFullName(Type type)
{
if (type.IsByRef) return "ref " + GetFullName(type.GetElementType());
if (type.DeclaringType != null) return GetFullName(type.DeclaringType) + "." + TypeName(type);
// HACK: Some constructed generic types report a FullName of null
if (type.FullName == null)
{
string[] argumentNames = Array.ConvertAll<Type, string>(
type.GetGenericArguments(),
GetFullName);
return string.Format(
"{0}[{1}]",
GetFullName(type.GetGenericTypeDefinition()),
string.Join(", ", argumentNames));
}
string name = TypeName(type.FullName);
if (type.IsGenericTypeDefinition)
{
name = string.Format(
"{0}[of {1}]",
name,
string.Join(", ", Array.ConvertAll<Type, string>(
type.GetGenericArguments(),
TypeName)));
}
return name;
}
示例6: create
/// <summary>
/// 生成类定义
/// </summary>
/// <param name="type">类型</param>
/// <param name="isPartial">是否部分定义</param>
/// <param name="isClass">是否建立类定义</param>
private void create(Type type, bool isPartial, bool isClass)
{
if (type.ReflectedType == null)
{
start.Add("namespace " + type.Namespace + @"
{");
end.Add(@"
}");
}
else
{
create(type.ReflectedType.IsGenericType ? type.ReflectedType.MakeGenericType(type.GetGenericArguments()) : type.ReflectedType, true, true);
}
if (isClass)
{
start.Add(@"
" + (type.IsPublic ? "public" : null)
+ (type.IsAbstract ? " abstract" : null)
+ (isPartial ? " partial" : null)
+ (type.IsInterface ? " interface" : " class")
+ " " + type.Name + (type.IsGenericType ? "<" + type.GetGenericArguments().joinString(", ", x => x.fullName()) + ">" : null) + @"
{");
end.Add(@"
}");
}
}
示例7: GetTypeDefinition
/// <summary>
/// Gets a correct type definition for a given type, ready for code generation, since
/// type.FullName doesnt represent generics in a way to be used in code generation.
/// Handles generics.
/// Based on: http://stackoverflow.com/questions/401681/how-can-i-get-the-correct-text-definition-of-a-generic-type-using-reflection
/// </summary>
/// <param name="type">the type to get definition for</param>
/// <returns>the string representation of the type definition</returns>
public static string GetTypeDefinition(Type type)
{
if (type.IsGenericParameter)
{
return type.Name;
}
if (!type.IsGenericType)
{
return type.FullName;
}
StringBuilder builder = new StringBuilder();
string name = type.Name;
int index = name.IndexOf("`");
builder.AppendFormat("{0}.{1}", type.Namespace, name.Substring(0, index));
builder.Append('<');
bool first = true;
for (int i = 0; i < type.GetGenericArguments().Length; i++)
{
Type arg = type.GetGenericArguments()[i];
if (!first)
{
builder.Append(',');
}
builder.Append(GetTypeDefinition(arg));
first = false;
}
builder.Append('>');
return builder.ToString();
}
示例8: GetConfigItemValueTypeEnum
/// <summary>
/// 获取配置项的值的类型的枚举
/// </summary>
/// <param name="valType">配置项值类型</param>
/// <returns></returns>
public static string GetConfigItemValueTypeEnum(Type valType)
{
//列表
if (typeof(IList).IsAssignableFrom(valType))
{
var genericArguments = valType.GetGenericArguments();
if (genericArguments.Length == 1 && valType.IsGenericType && genericArguments.First() == typeof(object))
return ValueTypeEnum.ObjectItemList.ToString();
return ValueTypeEnum.List.ToString();
}
//字典
if (typeof(IDictionary).IsAssignableFrom(valType))
{
var genericArguments = valType.GetGenericArguments();
if (genericArguments.Length == 2 && genericArguments.First() == typeof(string) && valType.IsGenericType && genericArguments.Last() == typeof(object))
return ValueTypeEnum.ObjectItemDictionary.ToString();
return ValueTypeEnum.Dictionary.ToString();
}
//基础类型
if (IsUnderlyingType(valType))
{
return ValueTypeEnum.Underlying.ToString();
}
//自定义配置实体
return ValueTypeEnum.Entity.ToString();
}
示例9: CreateInstance
/// <summary>
/// Create a new instance from a Type
/// </summary>
public static object CreateInstance(Type type)
{
try
{
CreateObject c = null;
if (_cacheCtor.TryGetValue(type, out c))
{
return c();
}
else
{
if (type.IsClass)
{
var dynMethod = new DynamicMethod("_", type, null);
var il = dynMethod.GetILGenerator();
il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
il.Emit(OpCodes.Ret);
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
_cacheCtor.Add(type, c);
}
else if (type.IsInterface) // some know interfaces
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>))
{
return CreateInstance(GetGenericListOfType(UnderlyingTypeOf(type)));
}
else if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IDictionary<,>))
{
var k = type.GetGenericArguments()[0];
var v = type.GetGenericArguments()[1];
return CreateInstance(GetGenericDictionaryOfType(k, v));
}
else
{
throw LiteException.InvalidCtor(type);
}
}
else // structs
{
var dynMethod = new DynamicMethod("_", typeof(object), null);
var il = dynMethod.GetILGenerator();
var lv = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloca_S, lv);
il.Emit(OpCodes.Initobj, type);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Box, type);
il.Emit(OpCodes.Ret);
c = (CreateObject)dynMethod.CreateDelegate(typeof(CreateObject));
_cacheCtor.Add(type, c);
}
return c();
}
}
catch (Exception)
{
throw LiteException.InvalidCtor(type);
}
}
示例10: CreateContract
protected override JsonContract CreateContract(Type objectType)
{
// This class special cases the JsonContract for just the Delta<T> class. All other types should function
// as usual.
if (objectType.IsGenericType &&
objectType.GetGenericTypeDefinition() == typeof(Delta<>) &&
objectType.GetGenericArguments().Length == 1)
{
var contract = CreateDynamicContract(objectType);
contract.Properties.Clear();
var underlyingContract = CreateObjectContract(objectType.GetGenericArguments()[0]);
var underlyingProperties =
underlyingContract.CreatedType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var property in underlyingContract.Properties)
{
property.DeclaringType = objectType;
property.ValueProvider = new DynamicObjectValueProvider()
{
PropertyName = this.ResolveName(underlyingProperties, property.PropertyName),
};
contract.Properties.Add(property);
}
return contract;
}
return base.CreateContract(objectType);
}
示例11: ReadJson
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
return null;
var keyType = objectType.GetGenericArguments()[0];
var keyValueType = keyType.BaseType.GetGenericArguments()[0];
var valueType = objectType.GetGenericArguments()[1];
var intermediateDictionaryType = typeof(Dictionary<,>).MakeGenericType(typeof(string), valueType);
var intermediateDictionary = (IDictionary)Activator.CreateInstance(intermediateDictionaryType);
serializer.Populate(reader, intermediateDictionary);
var valueProperty = keyType.GetProperty("Value");
var finalDictionary = (IDictionary)Activator.CreateInstance(objectType);
foreach (DictionaryEntry pair in intermediateDictionary)
{
object value;
if (keyValueType == typeof(Guid))
value = Guid.Parse(pair.Key.ToString());
else
value = Convert.ChangeType(pair.Key, keyValueType, null);
var key = Activator.CreateInstance(keyType);
valueProperty.SetValue(key, value, null);
finalDictionary.Add(key, pair.Value);
}
return finalDictionary;
}
示例12: CheckDoesModelTypeMatch
void CheckDoesModelTypeMatch(Type type, Type modelType)
{
if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(View<>))
{
if (modelType == null)
{
throw new InvalidOperationException(string.Format("The strongly typed view {0} expects a model type of {1} but was passed null.", ViewFile, type.GetGenericArguments()[0]));
}
if (!type.GetGenericArguments()[0].IsAssignableFrom(modelType))
{
throw new InvalidOperationException(string.Format("The strongly typed view {0} expects a model type of {1} but was passed model of type {2}.", ViewFile, type.GetGenericArguments()[0], modelType));
}
return;
}
}
if (type == typeof(View))
return;
// Recurse
CheckDoesModelTypeMatch(type.BaseType, modelType);
}
示例13: DeserializeToDictionary
private IDictionary DeserializeToDictionary(string input, Type type)
{
if (input.StartsWith("{", StringComparison.Ordinal) == true && input.EndsWith("}", StringComparison.Ordinal) == true)
{
string source = input;
input = input.Substring(1, input.Length - 2);
IDictionary dictionary = Activator.CreateInstance(type, true) as IDictionary;
// 获取键类型。
Type keyType = type.GetGenericArguments()[0];
// 获取值类型。
Type valueType = type.GetGenericArguments()[1];
foreach (var temp in JsonHelper.ItemReader(input))
{
string key;
string value;
JsonHelper.ItemSpliter(temp, out key, out value);
object oKey = DeserializeToObject(key, keyType);
if (dictionary.Contains(oKey) == false)
{
object oValue = DeserializeToObject(value, valueType);
dictionary.Add(oKey, oValue);
}
else
{
throw new JsonDeserializeException(source, type);
}
}
return dictionary;
}
else
{
throw new JsonDeserializeException(input, type);
}
}
示例14: IsProperInterface
private bool IsProperInterface(Type candidateInterface, Type openGenericInterfaceType, Type commandType)
{
return candidateInterface.IsGenericType &&
candidateInterface.GetGenericTypeDefinition() == openGenericInterfaceType &&
candidateInterface.GetGenericArguments().Length == 1 &&
MatchesType(candidateInterface.GetGenericArguments()[0], commandType);
}
示例15: TestAndAddRecursive
public static void TestAndAddRecursive(Type type, String declaringTypeNamespace, List<Type> valueTypes, List<String> namespaces)
{
if (type.IsGenericType)
{
if (type.GetGenericArguments() != null)
{
foreach (var genericArg in type.GetGenericArguments())
{
TestAndAddRecursive(genericArg, declaringTypeNamespace, valueTypes, namespaces);
}
}
return;
}
if (IsValueTypeNoEnumOrPrimitve(type) && !valueTypes.Contains(type) &&
type.Namespace != "System" && type.Namespace != declaringTypeNamespace)
{
valueTypes.Add(type);
}
if (!IsValueTypeNoEnumOrPrimitve(type) && type.Namespace != declaringTypeNamespace)
{
if (!ExcludedExternalNamespaces.Contains(type.Namespace) && !namespaces.Contains(type.Namespace))
{
namespaces.Add(type.Namespace);
}
else if (type.Namespace == "System" && type.Name == "Uri" && !namespaces.Contains("Windows.Foundation")) // Uri is special..
{
namespaces.Add("Windows.Foundation");
}
}
}