问题
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