giving a class instance the name of a variable

依然范特西╮ 提交于 2019-11-30 09:54:12

问题


How can i give a class instance the name of an existing variable. I am trying like this string hex = "BF43F"; Zeugh hex = new Zeugh(); but its wrong. I want to create an object BF43F with the properties of Zeugh class.


回答1:


Sounds like you want a Dictionary<string, Zeugh>. For example:

var d = new Dictionary<string, Zeugh>();
string hex = "BF43F"; 
d.Add(hex, new Zeugh());

(later)

Zeugh it = d["BF43F"];



回答2:


You can't declare two variables with the same name in the same scope.
If you later access the variable hex, how should the compiler know if you mean the "BF43F" string or the Zeugh object?

Or do you want an object with the same properties as a Zeugh object, but with one additional string property to save your string "BF43F" in?

You could create another class which inherits from Zeugh and has an additional string property:

public class ExtendedZeugh : Zeugh
{
    public string AdditionalString { get; set; }
}

Then, you can store your string "BF43F" in this property:

var hex = new ExtendedZeugh();
hex.AdditionalString = "BF43F";


来源:https://stackoverflow.com/questions/6976156/giving-a-class-instance-the-name-of-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!