如何使用反射,C#从类中获取值
本文关键字:获取 何使用 反射 | 更新日期: 2023-09-27 18:37:04
我有两个类
class FOO
{
public string Id{get;set;}
public Model Model{get;set}
}
class Model
{
public string Id
}
我需要在扩展方法中访问foo.Model.Id
在扩展方法中考虑T
是我们传递的类型FOO
我可以访问T.GetType().GetProperty("Model").GetValue(instance, null);
但是如何访问Foo.Model.Id
?
你只需要对下一个对象重复你的原始语句:
public static int GetId<T>(this T obj)
{
var model = obj.GetType().GetProperty("Model").GetValue(instance, null);
return (int)(model.GetType().GetProperty("Id").GetValue(instance, null));
}
但是为什么要把它放在一个通用的扩展方法中是有争议的。这是一个非常具体的属性链,所以没有多大意义。
一个更简单的方法是使用 dynamic
- 你根本不需要扩展方法:
dynamic d = obj;
int id = obj.Model.Id;
或者最好使用接口:
public interface IFoo
{
Model Model {get;set;}
}
public class Foo : IFoo
{
public string Id{get;set;}
public Model Model{get;set}
}
public static int GetId(this IFoo obj)
{
return obj.Model.Id;
}
你必须再次做同样的事情:
var model = instance.GetType().GetProperty("Model").GetValue(instance, null);
var id = model.GetType().GetProperty("Id").GetValue(model, null);