1

采取以下样本:

在此处输入图像描述

我想添加一个属性来PreferenceOption调用DataType,因为不同的实例PreferenceOption可能是boolstring

有没有办法做到这一点?如果是,如何?

我在想类似的东西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 };
    // ...
}
4

3 回答 3

3

使用泛型类;

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-04T14:02:20.980 回答
1

使用类型

public Type DataType { get; set; }

DataType = typeof(bool)
于 2012-12-04T14:02:33.710 回答
1

您可以将类设为 Generic

PreferenceOption<bool> WantsHouse;
PreferenceOption<string> HouseName;
于 2012-12-04T14:03:00.177 回答