C#使用反射与通用属性

use*_*105 3 c# generics reflection

我有一个使用通用属性的类.例如:

class Person
{
    public MyGenericProperty<string> Field1
    {
        get { return field1; }
        set { field1 = value; }
    }

    private MyGenericProperty<string> field1= new MyInheritedGenericProperty<string>("Alan1");
}
Run Code Online (Sandbox Code Playgroud)

我想在另一个类中使用这个类和反射,我有一个类似的方法

public void DoSomethingWithProperty(object sourceobject)
{
    foreach (var aProperty in sourceobject.GetType().GetProperties())
    {
        *if(aProperty.PropertyType == typeof(MyGenericProperty<>))*
        {
           *var obj = (MyGenericProperty<>)aProperty.GetValue(sourceobject, null);*
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

我有两个问题

1-如何进行通用属性的类型检查.在那个示例代码中if(aProperty.PropertyType == typeof(MyGenericProperty<>))不起作用.

MyGenericProperty的2-T可以是任何类,如何在不通过反射知道T的情况下转换MyGenericProperty类

var obj = (MyGenericProperty<>)aProperty.GetValue(sourceobject, null);
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助.

Jon*_*eet 8

首先,重要的是要了解你没有"通用属性" - 没有这样的东西.你有一个类型是泛型类型的属性......这不是一回事.(将其与通用类型或通用方法进行比较,在引入新类型参数方面,每种类型都是真正通用的.)

您可以使用以下代码进行测试:

if (aProperty.PropertyType.IsGenericType &&
    aProperty.GetGenericTypeDefinition() == typeof(MyGenericProperty<>))
Run Code Online (Sandbox Code Playgroud)

但至于铸造 - 它取决于你之后想要做什么.您可能希望声明一个非泛型基类型,MyGenericProperty<>其中包含所有不依赖于类型参数的成员.我通常会给它与通用类型(例如MyGenericProperty)相同的名称,而不给它类型参数.然后,如果您只需要其中一个成员,您可以使用:

if (aProperty.PropertyType.IsGenericType &&
    aProperty.GetGenericTypeDefinition() == typeof(MyGenericProperty<>))
{
    var value = (MyGenericProperty) aProperty.GetValue(sourceObject, null);
    // Use value
}
Run Code Online (Sandbox Code Playgroud)

但在那种情况下你可以使用Type.IsAssignableFrom:

if (typeof(MyGenericProperty).IsAssignableFrom(aProperty.PropertyType))
{
    var value = (MyGenericProperty) aProperty.GetValue(sourceObject, null);
    // Use value
}
Run Code Online (Sandbox Code Playgroud)

如果这些提示对您没有帮助,请详细说明您要做的事情.