采用以下示例:

我想向PreferenceOption添加一个名为DataType的属性,因为PreferenceOption的不同实例可以是bool或string等。
有没有办法做到这一点?如果是,是如何实现的?
我在想像public ValueType DataType { get; set; }这样的东西,但是在创建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 };
// ...
}发布于 2012-12-04 22:02:21
使用泛型类;
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"};发布于 2012-12-04 22:02:34
使用Type
public Type DataType { get; set; }
DataType = typeof(bool)发布于 2012-12-04 22:03:00
你可以把这个类变成一个Generic。
PreferenceOption<bool> WantsHouse;
PreferenceOption<string> HouseName;https://stackoverflow.com/questions/13704607
复制相似问题