【发布时间】:2014-11-23 13:45:42
【问题描述】:
我一直在玩泛型,并试图弄清楚如何(如果可能)通过动态传递对象来跨多个类使用单个方法。
我有几个类,Foo 和 Bar,如下所示:
[Serializable()]
public class Foo
{
private string m_Code;
private Bar m_Bar = new Bar();
public string Code
{
get { return m_Code; }
set { m_Code = value; }
}
public Bar Bar
{
get { return m_Bar; }
set { m_Bar = value; }
}
}
和
[Serializable()]
public class Bar
{
private string m_Name;
public string Name
{
get { return m_Name; }
set { m_Name = value; }
}
}
如果我用一些虚拟数据填充我的班级:
Foo.Code = "myFoo";
Foo.Bar.Name = "myBar";
我有一个从类返回值的通用方法:
public static object getItem<T>(T obj, string _Value)
{
try
{
object _Resolved = null;
_Resolved = obj.GetType().GetProperty(_Value).GetValue(obj, null);
return _Resolved;
}
catch (Exception ex)
{
return null;
}
}
像下面这样调用我的 getItem 方法可以正常工作。
string FooCode = Convert.ToString(getItem<Foo>(myFoo, "Code")) // returns "myFoo"
string BarName = Convert.ToString(getItem<Bar>(myFoo.Bar, "Name")) // returns "myBar"
我很好奇的是,是否有一种通过定义对象来寻址我的 getItem 方法的通用方法?
例如:
object myObject = Foo;
string FooCode = Convert.ToString(getItem<typeof(myObject)>(myObject, "Code")) // And this would returns "myFoo"
或:
object myObject = Bar;
string BarName = Convert.ToString(getItem<typeof(myObject)>(myObject, "Name")) // And this would returns "myBar"
【问题讨论】: