簡體   English   中英

將不同的數據類型分配給類的不同實例?

[英]Assigning different data types to different instances of a class?

采取以下示例:

在此處輸入圖片說明

我想向PreferenceOption添加一個稱為DataType的屬性,因為PreferenceOption不同實例可能是boolstring等。

有沒有辦法做到這一點? 如果是,怎么辦?

我在想類似public ValueType DataType { get; set; } public ValueType DataType { get; set; } 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 };
    // ...
}

使用泛型類;

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"};

使用類型

public Type DataType { get; set; }

DataType = typeof(bool)

您可以將類設為泛型

PreferenceOption<bool> WantsHouse;
PreferenceOption<string> HouseName;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM