如何获取C#对象中的属性,如javascript?

pwx*_*coo 0 c#

我想在C#中实现一个函数:

public string getName(object ob)
{
    // TODO: if object has "Name" attribute, return "Name".Value, else return null;
}
Run Code Online (Sandbox Code Playgroud)

当我调用这个函数时

string result1 = getName(new {Name = "jack", Age = 12})     // result1 = "jack"
string result2 = getName(new {Age = 12})      // result2 = null
Run Code Online (Sandbox Code Playgroud)

我知道用JavaScript或其他动态语言很容易实现......我很好奇它是否可以在C#中实现?

Rum*_*nsk 5

是的你可以.看看反思

public string getName(object ob)
{
    var type = ob.GetType();
    if (type.GetProperty("Name") == null) return null;
    else return type.GetProperty("Name").GetValue(ob, null);
}
Run Code Online (Sandbox Code Playgroud)