C#使用反射与通用属性

时间:2013-08-24 15:39:23

标签: c# generics reflection

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

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

    private MyGenericProperty<string> field1= new MyInheritedGenericProperty<string>("Alan1");
}

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

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;
}

我有两个问题

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

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

var obj = (MyGenericProperty<>)aProperty.GetValue(sourceobject, null);

感谢帮助。

1 个答案:

答案 0 :(得分:7)

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

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

if (aProperty.PropertyType.IsGenericType &&
    aProperty.GetGenericTypeDefinition() == typeof(MyGenericProperty<>))

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

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

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

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

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