2016-12-05 84 views
-2
var person = new Person(); 
Do(person.Firstname); 

static void Do(object prop) 
{ 
    //find out "Firstname"... 
} 

我想找出一个属性,的名字,我都进不去其父对象(人如上)的名字。可能吗?获得的财产

+1

你想知道这个人的名字吗?或者你基本上需要一个字符串“Firstname”吗? – devRicher

+1

您必须为“名称”设置单独的参数。没有任何东西阻止某人传递'Do(4)',在这种情况下,没有“名字”可以获得。 –

+1

如果你添加了你需要的名字,也许你可以得到一个实际上有用的答案。 –

回答

1

不,这是不可能的。您的Person.Firstname只是一个价值。该值对代码中的位置或来源一无所知。

+0

通过你的逻辑,将'int x'传递给一个函数使得不可能发现它是一个'int'。 – devRicher

+3

@devRicher:完全不一样。 'Firstname'是一个字符串。这就是'Do'可以知道的所有功能。它不知道它是一个字符串,恰好是名为'Firstname'的'Person'的属性。 OP想知道的是什么。那必须分开通过。 –

1

在C#6你可以使用nameof,但你必须将它传递给Do之前使用它:

Do(nameof(person.Firstname)); 

static void Do(object prop) 
{ 
    // prop is the string Firstname 
} 

如果你需要的价值和名字,你必须同时通过作为单独的参数:

Do(person.FirstName, nameof(person.Firstname)); 

static void Do(object prop, string name) 
{ 
    // name is the string Firstname 
    // prop is the value of person.Firstname 
} 
+0

好的,谢谢!它可能工作,如果没有别的可能,我会检查它... – dbol

0

也许这样的方法可以帮助你:

static void Do<TEntity, TProp>(TEntity entity, Expression<Func<TEntity, TProp>> property) 
{ 
    var member = property.Body as MemberExpression; 

    if (member != null) 
    { 
     var propertyName = member.Member.Name; 
     var propertyValue = property.Compile()(entity); 

     //Do something. 
    } 
} 

然后,你将能够做这样的事情:

Do(person, p => p.FirstName); 
Do(person, p => p.LastName); 
0

不能真正做到这一点有一个属性,但你可以用一种方法去做,包括不正是属性的作用的方法。例如

class Person 
{ 
    public string GetName() { return "John Doe"; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     var p = new Person(); 
     Do(p.GetName); //Notice no() after GetName 
    } 


    static void Do(Func<string> f) 
    { 
     Console.WriteLine(String.Format("The caller sent the value '{0}' via a method named {1}", f.Invoke(), f.Method.Name); 
    } 


}