采用以下示例:
我想向 PreferenceOption
添加一个名为 DataType
的属性,因为 PreferenceOption
的不同实例可能是 bool
或字符串
等
有没有办法做到这一点?如果是,如何?
我在想类似public ValueType DataType { get;放; }
,但是在创建 PreferenceOption
的实例时,例如:
PreferenceOption WantsHouse = new PreferenceOption () { PreferenceOption = "Want House?", Weighting = Weighting.Low, Type = bool };
这行不通,但应该能很好地说明我想做什么。
有什么建议吗?
编辑(答案):使用下面选择的答案,这是我现在使用的(为模糊的图像道歉!):
public enum Weighting { One, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten }
public class TenantPropertyPreferenceOption<T>
{
public T PreferenceOption { get; set; }
public Weighting Weighting { get; set; }
}
public class TenantPropertyPreferenceOptions
{
TenantPropertyPreferenceOption<bool> WantsHouse = new TenantPropertyPreferenceOption<bool> () { PreferenceOption = false, Weighting = Weighting.One };
// ...
}
最佳答案
使用泛型类;
public class PreferenceOption<T>
{
public T PreferenceOption {get;set;}
public string PreferenceOptionName {get;set;}
}
PreferenceOption WantsHouse = new PreferenceOption<bool> () { PreferenceOption = true, Weighting = Weighting.Low, PreferenceOptionName ="asd"};
PreferenceOption WantsHouse2 = new PreferenceOption<string> () { PreferenceOption = "this is a string", Weighting = Weighting.Low, PreferenceOptionName="qwe"};
关于c# - 将不同的数据类型分配给类的不同实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13704607/