猿问

C# 使用泛型和表达式树获取对象字段值

我有两个具有相似领域的课程:


Class Foo {

    string name;

    int val;

};


Class Bar {

    string name;

    int val;

};

有没有办法使用泛型来检索这些类的对象的字段名称和值?类似于以下内容:


string GetName<T> (T obj)

{

    //returns T.name

}

我想确保对此进行编译时检查,以防类字段发生更改。


更新:


我不控制类 Foo 和 Bar 的定义。它们将在图书馆中向我展示并且可以更改。


我可以使用以下内容:


Type myType = myObject.GetType();

var value = myType.GetProperty("name").GetValue(myObject, null);

但我认为这不会在编译时检查。


一只甜甜圈
浏览 450回答 2
2回答

繁花不似锦

如果您想要编译时安全,并且您不能修改Fooand Bar,则处理此问题的典型方法是使用重载:public string GetName(Foo o) { return o.Name; }public string GetName(Bar o) { return o.Name; }编译器会自动选择匹配参数类型的方法,所以你只需要调用它GetName(eitherObject);...而且它是类型安全的。你不能真正使用泛型,因为 Foo 和 Bar 缺少一个公开的通用接口Name。当然,您可以使用反射,但这意味着放弃编译时安全。

慕神8447489

这似乎是您可以使用继承的情况。如果这两个类具有相似的字段,您可以让它们实现一个具有所有共享字段的基类。这是一个例子:public class BaseEntity{&nbsp; &nbsp; int val;&nbsp; &nbsp; protected string name;&nbsp; &nbsp; public string Name&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return name; // Only get is exposed to prevent modifications&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}public class ClassA : BaseEntity{&nbsp; &nbsp;// Other fields or methods}public class ClassB : BaseEntity{&nbsp; &nbsp; // Other fields or methods}
随时随地看视频慕课网APP
我要回答