按名称获取字段

ina*_*key 6 .net c# reflection

我正在尝试创建一个可以从其对象返回字段的函数.

这是我到目前为止所拥有的.

public class Base
{
    public string thing = "Thing";
    public T GetAttribute<T>(string _name)
    {
        return (T)typeof(T).GetProperty(_name).GetValue(this, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

我理想的是打电话:

string thingy = GetAttribute<string>("thing");
Run Code Online (Sandbox Code Playgroud)

但是我有一种感觉,当我阅读这篇文章时我得到了错误的结论,因为我一直得到空引用异常.

Ham*_*jam 6

thing是一个领域而不是财产.你应该使用GetField方法而不是GetProperty.另一个问题是你正在寻找typeof(T).你应该寻找这个领域typeof(Base).

整个功能应该改为

public T GetAttribute<T>(string _name)
{
    return (T)GetType().GetField(_name).GetValue(this);
}
Run Code Online (Sandbox Code Playgroud)

如果您想要一个扩展方法来获取类型的字段值,您可以使用它

public static class Ex
{
    public static TFieldType GetFieldValue<TFieldType, TObjectType>(this TObjectType obj, string fieldName)
    {
        var fieldInfo = obj.GetType().GetField(fieldName,
            BindingFlags.Instance | BindingFlags.Static |
            BindingFlags.Public | BindingFlags.NonPublic);
        return (TFieldType)fieldInfo.GetValue(obj);
    }
}
Run Code Online (Sandbox Code Playgroud)

像它一样使用它

var b = new Base();
Console.WriteLine(b.GetFieldValue<string, Base>("thing"));
Run Code Online (Sandbox Code Playgroud)

使用BindingFlags将帮助您获得字段值,即使它是私有或静态字段.


kam*_*lod 6

第一件事 - thing是一个领域,而不是一个财产.

另一件事是您必须更改参数类型才能使其正常工作:

public class Base {

   public string thing = "Thing";

   public T GetAttribute<T> ( string _name ) {
      return (T)typeof(Base).GetField( _name ).GetValue (this, null);
   }   
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句 - 您可以通过引用实例来获取属性/字段值:

var instance = new Base();
var value = instance.thing;
Run Code Online (Sandbox Code Playgroud)