Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为类实例指定变量的名称_C#_Class_Naming - Fatal编程技术网

C# 为类实例指定变量的名称

C# 为类实例指定变量的名称,c#,class,naming,C#,Class,Naming,如何为类实例指定现有变量的名称。我试着这样做stringhex=“BF43F”;Zeugh hex=新Zeugh()

如何为类实例指定现有变量的名称。我试着这样做
stringhex=“BF43F”;Zeugh hex=新Zeugh()听起来像是想要一个
字典。例如:

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

不能在同一范围内声明两个同名变量。
如果以后访问变量
hex
,编译器如何知道您指的是“BF43F”字符串还是
Zeugh
对象

或者您想要一个与
Zeugh
对象具有相同属性的对象,但需要一个附加的字符串属性来保存字符串“BF43F”

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

public class ExtendedZeugh : Zeugh
{
    public string AdditionalString { get; set; }
}
var hex = new ExtendedZeugh();
hex.AdditionalString = "BF43F";
然后,您可以将字符串“BF43F”存储在此属性中:

public class ExtendedZeugh : Zeugh
{
    public string AdditionalString { get; set; }
}
var hex = new ExtendedZeugh();
hex.AdditionalString = "BF43F";

我想他想创建一个Zeugh类型的名为BF43F的变量,但他只有在运行时才知道该变量的名称(即BF43F)。正是这种情况。在这种情况下,我会选择Ben Voigt的方法。我如何引用字典中使用new Zeugh()创建的对象?@jayt:Like
d[“BF43F”]
如我的答案所示(也可以使用字符串变量)。如果您想知道某个特定名称是否存在,请使用
d.TryGetValue
。要查找所有名称/对象对,请使用
foreach(d中的KeyValuePair条目)
。实例通常没有名称。@jayt csharp:不清楚您想做什么。为什么变量名为
BF43F
?BF43F是我要创建的对象的id和名称。每个while循环都会给hex赋予不同的值。