Common class members in C #?

Hey, I think I have the wrong idea here, but I'm not sure which is better. 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;
    }
}

The type returned by the right side of the string 'this.value' is the string currently. I know that here it seems that I do not need to use anything other than a string type, but in the end I will parse the constructor, so that "this.value" can be a string, int, float or bool.

In any case, my compiler says: "It is not possible to convert" string "to" T ", so I assume that I am doing something very different.

Thanks.

+5
8

, ? , , :

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

, object ( ), :

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

, , . , .

+6

, . generic type : string, float, bool int - . , .

, , :

abstract class ConfigSetting
{ /* shared code here */  }

class TextSetting : ConfigSetting
{ /* Code here to handle string settings */ }

class BooleanSetting : ConfigSetting
{ /* ... 

.. , , factory , factory.

, . , List<T> -: ints, , , , .. , , , .

+7

T:

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

, generics , , , - .

, , , .

, , .

+1

,

DerivedMethods.configsettings.SettingGroups[heading].Settings[key].RawValue

- .

this.value, this.value - T , , .

- value, , bools, floats - .

public float GetFloatValue {
    get { return float.Parse(this.value); }
}

// etc
+1

, (configsettings.SettingGroups[heading].Settings[key].RawValue) . - T - . :

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

:

this.value = DerivedMethods.configsettings.SettingGroups[heading].Settings[key].RawValue;

T . RawValue . T.

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

T ? , , - .

0

string strValue = DerivedMethods.configsettings.SettingGroups[heading].Settings[key].RawValue;
this.value = (T)Convert.ChangeType(strValue, typeof(T), CultureInfo.InvariantCulture)

, , , . , Int32, Double ..

0
source

All Articles