获取实例名称 c#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16363753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:51:36  来源:igfitidea点击:

Get instance name c#

c#

提问by Yoan Dinkov

Maybe, this question is stupid, but in my specific situation i want to get instance name, so what i mean :

也许,这个问题很愚蠢,但在我的特定情况下,我想获得实例名称,所以我的意思是:

class Student
{
     private string name {get; private set;}

     public Student(string name) 
     {
         this.name = name 
     }

     public getInstanceName() 
     {
        //some function
     }

}

so when i make an student

所以当我成为学生时

   Student myStudent = new Student("John");

it's stupid but i want this

这很愚蠢,但我想要这个

 myStudent.getInstanceName(); // it should return 'myStudent'

采纳答案by elexis

This is now possible in C# 6.0:

这现在在 C# 6.0 中是可能的:

Student myStudent = new Student("John");
var name = nameof(myStudent); // Returns "myStudent"

This is useful for Code Contracts and error logging as it means that if you use "myStudent" in your error message and later decide to rename "myStudent", you will be forced by the compiler to change the name in the message as well rather than possibly forgetting it.

这对于代码契约和错误日志很有用,因为这意味着如果您在错误消息中使用“myStudent”,然后决定重命名“myStudent”,编译器将强制您更改消息中的名称,而不是可能忘记了。

回答by Reed Copsey

This is not possible in C#. At runtime, the variable names will not even exist, as the JIT removes the symbol information.

这在 C# 中是不可能的。在运行时,变量名甚至不存在,因为 JIT 删除了符号信息。

In addition, the variable is a reference to the class instance - multiple variables can reference the same instance, and an instance can be referenced by variables of differing names throughout its lifetime.

此外,变量是对类实例的引用——多个变量可以引用同一个实例,并且一个实例可以在其整个生命周期中被不同名称的变量引用。

回答by Niels Keurentjes

No, this is not possible, because it's totally ridiculous. An object can never, in any way, know the name of the variable you happen to assign it to. Imagine:

不,这是不可能的,因为这完全是荒谬的。以任何方式,对象永远无法知道您碰巧将其分配给的变量的名称。想象:

Student myStudent = new Student("John");
Student anotherStudent = myStudent;
Console.Write(anotherStudent.getInstanceName());

Should it say myStudentor anotherStudent? Obviously, it has no clue. Or funnier situations:

应该说myStudent还是anotherStudent?显然,它没有任何线索。或者更有趣的情况:

School mySchool = new School("Harvard");
mySchool.enroll(new Student("John"));
Console.Write(mySchool.students[0].getInstanceName());

I really would like to know what this would print out.

我真的很想知道这会打印出什么。

回答by Jean-Bernard Pellerin

Give this a try

试试这个

string result = Check(() => myStudent);

static string Check<T>(Expression<Func<T>> expr)
{
    var body = ((MemberExpression)expr.Body);
    return body.Member.Name;
}

Or

或者

GetName(new { myStudent });

static string GetName<T>(T item) where T : class 
{
  return typeof(T).GetProperties()[0].Name;
}

回答by p.s.w.g

Variable names exist only for your benefit while coding. Once the the code is compiled, the name myStudentno longer exists. You can track instance names in a Dictionary, like this:

变量名称的存在只是为了您在编码时的利益。一旦代码被编译,这个名字myStudent就不再存在。您可以在字典中跟踪实例名称,如下所示:

var students = new Dictionary<string, Student>();
var students["myStudent"] = new Student("John");

// Find key of first student named John
var key = students.First(x => x.Value.Name == "John").Key; // "myStudent"

回答by kernowcode

No, but you could do this

不,但你可以这样做

var myStudent = new Student("John").Named("myStudent");
var nameOfInstance = myStudent.Name();

public static class ObjectExtensions
{
    private static Dictionary<object,string> namedInstances = new Dictionary<object, string>(); 

    public static T Named<T>(this T obj, string named)
    {
        if (namedInstances.ContainsKey(obj)) namedInstances[obj] = named;
        else namedInstances.Add(obj, named);
        return obj;
    }

    public static string Name<T>(this T obj)
    {
        if (namedInstances.ContainsKey(obj)) return namedInstances[obj];
        return obj.GetType().Name;
    }
}

回答by whoisj

This question is very old, but the answer changed with the release of .Net Framework 4.6. There is now a nameof(..)operator which can be used to get the string value of the name of variables at compile time.

这个问题很老了,但随着 .Net Framework 4.6 的发布,答案发生了变化。现在有一个nameof(..)运算符可用于在编译时获取变量名称的字符串值。

So for the original question C# nameof(myStudent) // returns "myStudent"

所以对于原来的问题 C# nameof(myStudent) // returns "myStudent"

回答by K. Summers

So I've been searching around for about a week trying to figure out how to do this. While gathering bits and pieces of stuff I didn't know I found a relatively simple solution.

所以我一直在寻找大约一周的时间,试图弄清楚如何做到这一点。在收集我不知道的零碎东西时,我找到了一个相对简单的解决方案。

I think the original poster was looking for something like this, because if you have to use the name of the class to find out the name of the class then what's the point..

我认为原始海报正在寻找这样的东西,因为如果您必须使用班级名称来找出班级名称,那有什么意义..

For those saying "It's not possible" and "Why would you want to.." my particular reason is for a class library where I have a class that the app developer can call the instances whatever they want, and it's meant to have multiple instances with different names. So I needed a way to be able to identify those instances so I can use the right one for the circumstance.

对于那些说“这是不可能的”和“你为什么要......”的人,我的特殊原因是一个类库,我有一个类,应用程序开发人员可以随意调用实例,并且它意味着有多个实例用不同的名字。所以我需要一种方法来识别这些实例,以便我可以根据情况使用正确的实例。

    public static List<Packet> Packets = new List<Packet>();
    public class Packet
    {
        public Packet(string Name)
        {
            Packets.Add(this);
            name = Name;
        }
        internal string _name;
        public string name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

It does require that they pass in the name of the instance as I've not yet figured out how to acquire the name they're using from inside the constructor. That is likely the thing that isn't possible.

它确实要求它们传入实例的名称,因为我还没有弄清楚如何从构造函数内部获取它们正在使用的名称。这是可能的事情是不可能的

    public Packet MyPacket = new Packet("MyPacket");

This creates the instance, stores a reference to it in Packets and saves it's name in the newly created instance.

这将创建实例,在 Packets 中存储对它的引用,并将其名称保存在新创建的实例中。

To get the name associated with the Packet and connect it to a variable..

要获取与数据包关联的名称并将其连接到变量..

    Packet NewName = Packets[Packets.FindIndex(x => x.name == "MyPacket");

Whether you use the same variable name or a new one doesn't really matter, it's just linking the instance you want to it.

无论您使用相同的变量名还是新的变量名都没有关系,它只是将您想要的实例链接到它。

    Console.WriteLine(NewName.name); // Prints MyPacket

For instances with the same name you would have to come up with some other way to tell them apart, which would require another list and some logic to determine which one you want.

对于具有相同名称的实例,您将不得不想出一些其他方法来区分它们,这将需要另一个列表和一些逻辑来确定您想要哪个。