Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将属性转换为it';她叫什么名字?_C# - Fatal编程技术网

C# 如何将属性转换为it';她叫什么名字?

C# 如何将属性转换为it';她叫什么名字?,c#,C#,有人能帮我解决这个问题吗 public class MyClass { public int MyProperty{ get; set; } private void MyMethod() { // here I wat to get the name of MyProperty. // string name = "MyProperty"; <-- I don't want to hardcode it like this. } } 公共类MyCla

有人能帮我解决这个问题吗

public class MyClass
{

public int MyProperty{ get; set; }


  private void MyMethod()
  {
    // here I wat to get the name of MyProperty.
    // string name = "MyProperty"; <-- I don't want to hardcode it like this.
  } 
}
公共类MyClass
{
公共int MyProperty{get;set;}
私有void MyMethod()
{
//在这里我想知道我的财产的名称。

//string name=“MyProperty”一个选项是使用表达式树:

var name = ExpressionTrees.GetPropertyName<MyClass, int>(x => x.MyProperty);

...


public static class ExpressionTrees
{
    public static string GetPropertyName<TSource, TTarget>
         (Expression<Func<TSource, TTarget>> expression)
    {
        ...
    }
}
您可以在执行时检测到这一点,但不能在编译时检测到。还有性能方面的问题——这不会很糟糕,但可能并不理想


取决于您的需求(在本例中,这正是您想要标识该属性而不是另一个属性的原因)然后其他方法也可以很好地工作,例如属性。

您可以通过反射来获得它。如果您的类有多个属性,请使用自定义属性标记相关的属性。+1.表达式树很酷……即使不清楚OP是想要表达式树的编译时安全性,还是想要类的属性名称。谢谢。是的,我通常使用expressionTrees类来获取名称。我只是好奇有没有另一种更简单的方法来获取属性名称而不将MyClass作为参数发送,因为我认为我们在类本身中。也许我想问的是“类本身能知道它的属性的名称吗?”@dav:不,目前对其他成员来说没有什么能比得上
typeof
。也许有一天。。。
ExpressionTrees.GetPropertyName<MyClass, int>(x => 0);