为类实例指定变量的名称

本文关键字:变量 实例 | 更新日期: 2023-09-27 18:05:01

如何为类实例提供现有变量的名称?我正在努力像这个string hex = "BF43F"; Zeugh hex = new Zeugh();,但这是错误的。我想创建一个对象BF43F与Zeugh类的属性。

为类实例指定变量的名称

听起来你想要一个Dictionary<string, Zeugh>。例如:

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

(后来)

Zeugh it = d["BF43F"];

不能在同一作用域中声明两个同名的变量。
如果稍后访问变量hex,编译器如何知道您是指"BF43F"字符串还是Zeugh对象?

或者你想要一个与Zeugh对象具有相同属性的对象,但有一个额外的字符串属性来保存你的字符串"BF43F"?

你可以创建另一个继承自Zeugh的类,并且有一个额外的字符串属性:

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

然后,你可以在这个属性中存储你的字符串"BF43F":

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