我有一个使用通用属性的类.例如:
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)
谢谢你的帮助.