相关疑难解决方法(0)

如何获取特定属性的PropertyInfo?

我想获取特定属性的PropertyInfo.我可以用:

foreach(PropertyInfo p in typeof(MyObject).GetProperties())
{
    if ( p.Name == "MyProperty") { return p }
}
Run Code Online (Sandbox Code Playgroud)

但必须有办法做类似的事情

typeof(MyProperty) as PropertyInfo
Run Code Online (Sandbox Code Playgroud)

在那儿?还是我坚持做一个类型不安全的字符串比较?

干杯.

c# reflection

77
推荐指数
3
解决办法
6万
查看次数

如何从C#(2.0)中的属性获取属性的名称

我知道我可以有一个属性,但这比我想去的工作更多......而且不够通用.

我想做点什么

class Whotsit
{
    private string testProp = "thingy";

    public string TestProp 
    {
        get { return testProp; }
        set { testProp = value; }
    }

}

...

Whotsit whotsit = new Whotsit();
string value = GetName(whotsit.TestProp); //precise syntax up for grabs..
Run Code Online (Sandbox Code Playgroud)

在哪里我期望价值等于"TestProp"

但我不能为我的生活找到正确的反射方法来编写GetName方法...

编辑:我为什么要这样做?我有一个类来存储从'name','value'表中读取的设置.这由基于反射的通用方法填充.我很想反写...

/// <summary>
/// Populates an object from a datatable where the rows have columns called NameField and ValueField. 
/// If the property with the 'name' exists, and is not read-only, it is populated from the …
Run Code Online (Sandbox Code Playgroud)

c# reflection properties

6
推荐指数
1
解决办法
1014
查看次数

标签 统计

c# ×2

reflection ×2

properties ×1