Reputation: 13616
I have a class named config with two string fields named key paramValue and parameterPath.
When I apply the ChooseType method of the class, the method has to return one variable paramValue in different types (Int or bool or String).
I implemented it as follow:
class ConfigValue
{
public string paramPath;
private string paramValue;
public enum RetType {RetInt, RetBool, RetString};
public T PolimorphProperty<T>(RetType how)
{
{
switch (how)
{
case RetType.RetInt:
return (dynamic)int.Parse(paramValue);
case RetType.RetBool:
return (dynamic)Boolean.Parse(paramValue);
case RetType.RetString:
return (T)(object)paramValue;
default:
throw new ArgumentException("RetType not supported", "how");
}
}
}
}
My question is how can i access to the PolimorphProperty method in ConfigValue class, to retrive for examlple paramValue Int type.
Upvotes: 0
Views: 83
Reputation: 2681
I think following code best matches what you want (i have tested it before writing here...)
public T PolimorphProperty<T>()
{
object tt = Convert.ChangeType(paramValue, typeof(T));
if (tt == null)
return default(T);
return (T) tt;
}
And you can call the code like this:
int ret = cv.PolimorphProperty<int>();
Upvotes: 1
Reputation: 56536
Having both T
and RetType
is redundant. It should be something like this:
class ConfigValue
{
public string paramPath;
private string paramValue;
public T PolimorphProperty<T>()
{
return (T)Convert.ChangeType(paramValue, typeof(T));
}
}
Call it like configValue.PolimorphProperty<int>()
.
Or if you need to implement the type conversion manually, you can do something like this:
class ConfigValue
{
public string paramPath;
private string paramValue;
public T PolimorphProperty<T>()
{
if (typeof(T) == typeof(MySpecialType))
return (T)(object)new MySpecialType(paramValue);
else
return (T)Convert.ChangeType(paramValue, typeof(T));
}
}
Upvotes: 4