在C#泛型类成员? [英] Generic Class Members in C#?

查看:258
本文介绍了在C#泛型类成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我想我有错误的想法在这里,但我不知道什么是最好的。我想用构件变量,可以是任何类型的,这取决于所需要的,此时的类。到目前为止,我有这样的事情:

Hey, I think I have the wrong idea here, but I'm not sure what is best. I want a class with a member variable that can be of any type, depending on what is needed at the time. So far, I have something like this:

    public class ConfigSetting<T> {
    private T value;

    public T GetValue() {
        return value;
    }
    public void ChangeValue() {

    }

    public ConfigSetting(string heading, string key) {
        this.value = DerivedMethods.configsettings.SettingGroups[heading].Settings[key].RawValue;
    }
}



通过的这个右侧的返回类型.value的'行是一个字符串,目前。我知道这里好像我有没有必要使用比字符串类型以外的任何其他,但最终我将扩大的构造,使得THIS.VALUE可能是一个字符串,整数,浮点,或布尔。

The type returned by the right side of the 'this.value' line is a string, currently. I know here it seems like I have no need to use anything other than the string type, but eventually I will expand the constructor, such that 'this.value' could be a string, int, float, or bool.

不管怎样,我的编译器说:无法将'字符串'到'T',所以我认为我做的事情很落后。

Anyway, my compiler says "Cannot convert 'string' to 'T'", so I assume I'm doing something very backwards.

感谢您。

推荐答案

那么,转换你期望它适用?如果您所期望的价值已经是正确的类型,你可以这样做:

Well, what conversion did you expect it to apply? If you expect the value to already be of the right type, you could do:

object tmp = DerivedMethods.configsettings.SettingGroups[heading].Settings[key].RawValue;
this.value = (T) tmp;

请注意,你必须去通过对象隐式(如下)或有明确的转换:

Note that you have to go through object either implicitly (as here) or with an explicit cast:

this.value = (T)(object) DerivedMethods.configsettings... (etc);



这组提供通用类型的转换是比较有限的。但是,如果原始值是真正正确的它应该工作。

The set of conversions provided for generic types is somewhat limited. But it should work if the original value is genuinely correct.

这篇关于在C#泛型类成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆