简体   繁体   English

我如何获得一个类名变量

[英]how do i get a class name variable

Im trying to get the class variable name 我正在尝试获取类变量名称

static void Main()
{
    TaskAction m_first = new TaskAction();
    m_first.Increment();
    m_first.Increment();

    TaskAction m_Second = new TaskAction();
    m_Second.Increment();

}

public class TaskAction
{
    private int m_Current;

    public TaskAction()
    {
        m_Current = 0;

    }

    public void Increment()
    {
        m_Current++;
        write(" TaskAction " + vairableName + " "  + m_Current);       
    }
}

i want to it to write out: 我想写出来:

TaskAction m_first 1 TaskAction m_first 1

TaskAction m_first 2 TaskAction m_first 2

TaskAction m_second 1 TaskAction m_second 1

Retrieving metadata about your program like that is both complex and unnecessary, just add the name by passing it to the constructor. 像这样检索有关程序的元数据既复杂又不必要,只需将名称传递给构造函数即可。

static void Main()
{
    TaskAction m_first = new TaskAction("m_first");
    m_first.Increment();
    m_first.Increment();

    TaskAction m_Second = new TaskAction("m_Second");
    m_Second.Increment();

}

public class TaskAction
{
    private int m_Current;
    private string m_taskName;

    public TaskAction(string taskName)
    {
        m_taskName = taskName;
        m_Current = 0;
    }

    public void Increment()
    {
        m_Current++;
        write(" TaskAction " + m_taskName + " "  + m_Current);       
    }
}

Short Answer: You can't. 简短的回答:不能。

Long Answer: 长答案:

Technically, it's possible to determine a variable name by inspecting the IL (the intermidate language created by the C# compiler), but this operation is hard and error-prone. 从技术上讲,可以通过检查IL(由C#编译器创建的中间语言)来确定变量名,但是此操作很困难且容易出错。 Also, you ignore some important questions: 此外,您忽略了一些重要的问题:

  • First of all, as already asked here: Why? 首先,正如这里已经问过的: 为什么? how such thing will enhance your program? 这样的事情将如何改善您的程序?

  • Each instance of the class can have multiple variables pointing to it (see my answer about types in .NET here ). 类的每个实例都可以有(见我的关于.NET类型的答案多个变量指向它在这里 )。 Which of them you want to get? 您想得到哪一个? For example, consider the following program: 例如,考虑以下程序:

var v1 = new TaskAction();
var c2 = new TaskAction();
c1.Increment(); // 1 c1
c2 = c1;
c2.Increment(); // 2 c1? 2 c2? 2 c1 c2?
  • By doing so, you break the encapsulation in a difficult way - any reflection breaks the encapsulation, and really don't use it unless you really need it - but so much? 这样一来,您将以一种困难的方式破坏封装-任何反射都会破坏封装,除非您确实需要,否则实际上不使用它-这么多吗? Reflection breaks the hidden information about the private interface, you question breaks the internal interface! 反射破坏有关专用接口的隐藏信息,您要破坏内部接口!

Since you didn't give enough information, I can't know why you tought you need that. 由于您没有提供足够的信息,所以我不知道您为什么要这么做。 But here is some solutions: 但是这里有一些解决方案:

  • If you want, for example, logging with categories - simply pass the category to the constructor, as sugegsted above. 例如,如果要使用类别进行日志记录-只需将类别传递给构造函数即可,如上文所述。

  • If you want to know which type the variable is - using its name is very very very bad approach, even though you have conventions - use polymorphism instead (best), or, at least, check the type with is / as , for example: 如果你想知道的变量是哪种类型的-使用它的名字是非常非常非常糟糕的做法,即使你有约定-利用多态性,而不是(最好的),或者,至少,有检查类型is / as ,例如:

if (this is Drived)
{
    ((Drived)this).SomeDrivedMethod();
}

Note that it breaks the OOP principles: a class shouldn't know about its drived classes. 请注意,这违反了OOP原则:类不应了解其驱动类。

Hope this helped you. 希望这对您有所帮助。 Have a nice day! 祝你今天愉快!

Edit: 编辑:

For your purpose, you can do one of the following: 为了您的目的,您可以执行以下任一操作:

Best - debug your code, see the call stack etc. 最好-调试代码,查看调用堆栈等。

Worse - print the caller method name, instead of the object name. 更糟-打印调用方方法名称,而不是对象名称。 It's can be done using System.Runtime.CompilerServices.CallerMemberNameAttribute : 可以使用System.Runtime.CompilerServices.CallerMemberNameAttribute来完成:

void Increment([System.Runtime.CompilerServices.CallerMemberName] string caller = null)
{
    // Default value to `caller` is neccessary
    // ...
    Console.WriteLine("Caller: {0}", caller);
}

Note: the compiler fills the caller parameter, not in runtime. 注意:编译器将填充caller参数,而不是在运行时填充。

如果要唯一标识类对象或使用自定义构造函数为类提供名称,请​​获取object.GetHashCode()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何创建变量名称为'toString'类型的动态类? - How do I create a dynamic class with variable name of type 'toString'? 如何获取数组变量另存为文件名输出? - How do I get a array variable to save as the file name output? NLog-如何以编程方式获取调用方的类名和方法? - NLog - How do I get caller class name and method programmatically? 如何在类内部获取对象的变量名? - How to get variable name of object inside class? 如果我只有类名和dll名称,如何获得完全限定的程序集引用? - How do I get a fully-qualified assembly reference if I only have the class name and dll name? 如何获取窗口类名称的长度,以便知道要分配多大的缓冲区? - How do I get the length of a window class name so I know how large of a buffer to allocate? 如何从基类执行方法时从某个类中获取变量? - How do I get a variable from a dervied class to be used when executing a method from a base class? 如何本地化类显示名称 - How do I Localize a Class Display Name 当我有类但子类名称为字符串时,如何从子类获取属性 - How do I get the properties from a subclass when I have the class but subclass name as a string 获取类中声明的变量名 - Get the declared variable name in a class
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM