Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果属性是反射中的集合,如何知道它的类型?_C#_Reflection - Fatal编程技术网

C# 如果属性是反射中的集合,如何知道它的类型?

C# 如果属性是反射中的集合,如何知道它的类型?,c#,reflection,C#,Reflection,它返回“System.Collections.Generic.list”。但我的期望是将类型作为MyClass 我也试过这样的方法 Type t = obj.GetType(); 但它返回错误,因为集合属性的值为null,因此无法获取类型 在这种情况下,如何获取集合属性的类型 请帮帮我 提前感谢。使用propertyInfo.PropertyType而不是propertyInfo.GetValue(obj,null).GetType(),即使属性值为null,它也应该为您提供属性类

它返回“System.Collections.Generic.list”。但我的期望是将类型作为MyClass

我也试过这样的方法

      Type t = obj.GetType();
但它返回错误,因为集合属性的值为null,因此无法获取类型

在这种情况下,如何获取集合属性的类型

请帮帮我


提前感谢。

使用
propertyInfo.PropertyType
而不是
propertyInfo.GetValue(obj,null).GetType()
,即使属性值为
null
,它也应该为您提供属性类型

所以当你有一节课

        foreach(PropertyInfo propertyInfo in obj.GetProperties())
        {
             if(propertyInfo.IsGenericType)
             {
              Type t = propertyInfo.GetValue(obj,null).GetType().GetGenericArguments().First();
             }
        }

将在
typeArg
中为您提供值
System.String
(作为
System.Type
实例)使用
propertyInfo.PropertyType
,该属性的名称为
IsGenericType
,例如:

var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example
var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0];

你能澄清一下吗,它看起来不像是可以编译的。它不是一个完整的代码。假设这种情况,请给我答案。我使用了你建议的方法。但是如果集合属性为null,我想得到类型。我相信你首先为类创建contractor.contractor(){List dd=new List();dd=null;}是,返回System.Collections.Generic.List。我需要的是属性的类型,而不是集合。您应该能够调用
GetGenericArguments().First()
on
propertyInfo.PropertyType
就像您自己的代码示例一样。是的,我调用了。它返回System.Collections.Generic.List。我添加了一个示例,该示例应该能够澄清我的确切意思。
public class Foo {
    public List<string> MyProperty { get; set; }
}
var propertyInfo = obj.GetType().GetProperty("MyProperty"); // or find it in a loop like in your own example
var typeArg = propertyInfo.PropertyType.GetGenericArguments()[0];
if (propertyInfo.PropertyType.IsGenericType)
{
    // code ...
}