【问题标题】:how to get varriable name over another one c#?如何在另一个 c# 上获取变量名?
【发布时间】:2020-12-10 12:29:37
【问题描述】:
string MyVar1 = "bilah bilah";
dosometing(MyVar1);

    void dosometing(object MyObject)
    {
       string VarName = nameof(MyObject);   // it givess : "MyObject"
    }

但我期待“MyVar1”有办法吗?使用动态?还是参考?

【问题讨论】:

  • 我认为没有办法,而且我没有看到 任何 实际用例 - 你想达到什么目的?不管是什么,我敢打赌至少有十几种更好的方法。
  • 如果调用者是dosometing("Hello");dosometing(MyVar1 + AnotherVar);,你期望会发生什么?
  • 看看这个。可能重复:stackoverflow.com/questions/72121/…
  • 这能回答你的问题吗? Finding the variable name passed to a function
  • 您的MyVar1 变量就是这样,一个变量。由于string 是一个引用类型,它持有对该文字字符串的引用。在 C# 中,参数是按值传递的,因此引用按值传递并复制到 MyObject 变量。此时,有两个不同的变量指向同一个对象。除此之外,它们之间没有任何关系。 nameof 运算符允许编译器为程序员提供范围内的变量(或类或..)的名称。没有办法随心所欲,根本不符合设计

标签: c# object dynamic reflection system.reflection


【解决方案1】:

这是不可能的。但是你可以这样做:

string MyVar1 = "bilah bilah";
dosometing(MyVar1, nameof(MyVar1));

void dosometing(string MyString, string VarName)
{
   // MyString holds the value
   // VarName holds the variable name
}

【讨论】:

  • 实际上我正在这样做,我的目标是减少这段代码,因为我经常将它用于数据库操作。现在我看到这是不可能的,并且重复,抱歉
【解决方案2】:

也许这些信息对你有用。

由于您想要 propertyvaluename 已更改,您可以将方法 dosomething 移动到属性的 setter 内。

(注意:我假设您实际上是在使用属性而不是您的问题中显示的局部变量,您的问题只是简化了)

所以是这样的:

public class Foo
{
    private string _myVar1;
    public string MyVar1
    {
        get => _myVar1;
        set
        {
            _myVar1 = value;
            DoSomething(value);
        }
    }


    private void DoSomething(string value, [CallerMemberName]string propertyName = "")
    {
         Console.WriteLine(value);
         Console.WriteLine(propertyName);
    }
}

属性CallerMemberName需要使用System.Runtime.CompilerServices

更多信息可以在这里找到:https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute

在此处查看实际操作:https://dotnetfiddle.net/YvqqdP

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-21
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多