c# - 将不同的数据类型分配给类的不同实例?

标签 c#

采用以下示例:

enter image description here

我想向 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/

相关文章:

c# - 有没有办法在对象实例化后立即调用方法?

c# - 向 MDB 插入和更新数据

c# - 记住并恢复 WPF 窗口的屏幕、WindowState 和位置?

c# - 单击按钮后继续在列表中添加项目

c# - .net DispatcherTimer 重复触发刻度事件

c# - unity EditorGUI.PropertyField 无法完全禁用数组或列表

c# - 如何制作可以使用 * 相乘的结构

C# Cmdlet 调用 GetChildItem

c# - 从没有管理员权限的用户应用程序访问全局互斥/信号量

c# - 异步调用并行 for 循环