如何使用反射从类中获取值,c#
我有两节课如何使用反射从类中获取值,c#,c#,.net,winforms,C#,.net,Winforms,我有两节课 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(实例,null) 但是如何访问Foo.Model.Id?您必须再次执
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(实例,null)代码>
但是如何访问Foo.Model.Id
?您必须再次执行相同的操作:
var model = instance.GetType().GetProperty("Model").GetValue(instance, null);
var id = model.GetType().GetProperty("Id").GetValue(model, null);
您只需为下一个对象重复原始语句:
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));
}
或者最好使用一个接口:
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;
}
对刚刚得到的模型的实例重复该过程。结果是一个模型实例。对它执行同样的操作以获得ID。更好的是,使用dynamic
来避免整个混乱。这样的代码看起来确实很奇怪,而且速度会非常慢。也许您应该使用泛型,传递接口而不是具体的类,或者两者兼而有之。或者您可以传递一个访问器lambda来检索值,而不使用reflectionOr,或者将T
限制为某个基类类型或接口。您可以发布完整的扩展方法吗?也许这可以不用思考就可以做到。
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;
}