首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将不同的数据类型分配给一个类的不同实例?

将不同的数据类型分配给一个类的不同实例?
EN

Stack Overflow用户
提问于 2012-12-04 21:59:53
回答 3查看 95关注 0票数 1

采用以下示例:

我想向PreferenceOption添加一个名为DataType的属性,因为PreferenceOption的不同实例可以是boolstring等。

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

我在想像public ValueType DataType { get; set; }这样的东西,但是在创建PreferenceOption的实例时,像这样:

代码语言:javascript
复制
PreferenceOption WantsHouse = new PreferenceOption () { PreferenceOption = "Want House?", Weighting = Weighting.Low, Type = bool };

这不起作用,但应该给我一个好的想法,我想做什么。

有什么建议吗?

编辑(答案):使用下面选择的答案,这是我现在使用的(很抱歉图像模糊!):

代码语言:javascript
复制
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 };
    // ...
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-12-04 22:02:21

使用泛型类;

代码语言:javascript
复制
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"};
票数 3
EN

Stack Overflow用户

发布于 2012-12-04 22:02:34

使用Type

代码语言:javascript
复制
public Type DataType { get; set; }

DataType = typeof(bool)
票数 1
EN

Stack Overflow用户

发布于 2012-12-04 22:03:00

你可以把这个类变成一个Generic

代码语言:javascript
复制
PreferenceOption<bool> WantsHouse;
PreferenceOption<string> HouseName;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13704607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档