[英]c# Reflection - Find the Generic Type of a Collection
我正在反映一个属性'Blah',它的Type是ICollection
public ICollection<string> Blah { get; set; }
private void button1_Click(object sender, RoutedEventArgs e)
{
var pi = GetType().GetProperty("Blah");
MessageBox.Show(pi.PropertyType.ToString());
}
这给了我(正如你所期望的那样!) ICollection<string>
...
但实际上我想获得集合类型即ICollection
(而不是ICollection<string>
) - 有谁知道我该怎么做呢?
例如,您需要查看GetGenericTypeDefinition :
List<String> strings=new List<string>();
Console.WriteLine(strings.GetType().GetGenericTypeDefinition());
foreach (var t in strings.GetType().GetGenericArguments())
{
Console.WriteLine(t);
}
这将输出:
System.Collections.Generic.List`1 [T]
System.String
您正在寻找GetGenericTypeDefinition
方法:
MessageBox.Show(pi.PropertyType.GetGenericTypeDefinition().ToString());
我有一个类似但更复杂的问题......我想确定一个类型是否可以动态分配给集合类型成员或数组类型成员。
因此,如果要添加的对象的类型可分配给集合或数组类型成员,则有更好的方法如何通过验证动态获取成员类型的集合或数组:
List<IComparable> main = new List<IComparable>() { "str", "řetězec" };
IComparable[] main0 = new IComparable[] { "str", "řetězec" };
IEnumerable collection = (IEnumerable)main;
//IEnumerable collection = (IEnumerable)main0;
string str = (string) main[0];
if (collection.GetType().IsArray)
{
if (collection.GetType().GetElementType().IsAssignableFrom(str.GetType()))
{
MessageBox.Show("Type \"" + str.GetType() + "\" is ok!");
}
else
{
MessageBox.Show("Bad Collection Member Type");
}
}
else
{
if (collection.GetType().GenericTypeArguments[0].IsAssignableFrom(str.GetType()))
{
MessageBox.Show("Type \"" + str.GetType() + "\" is ok!");
}
else
{
MessageBox.Show("Bad Collection Member Type");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.