加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 按名称获取字段

发布时间:2020-12-15 17:47:24 所属栏目:百科 来源:网络整理
导读:我正在尝试创建一个可以从其对象返回字段的函数. 这是我到目前为止所拥有的. public class Base{ public string thing = "Thing"; public T GetAttributeT(string _name) { return (T)typeof(T).GetProperty(_name).GetValue(this,null); }} 我理想的是打电
我正在尝试创建一个可以从其对象返回字段的函数.

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

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

我理想的是打电话:

string thingy = GetAttribute<string>("thing");

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

解决方法

第一件事 – 事情是一个领域,而不是一个财产.

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

public class Base {

   public string thing = "Thing";

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

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

var instance = new Base();
var value = instance.thing;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读