[英]How can I access to the method in class that returns a Generic Type
I have a class named config with two string fields named key paramValue and parameterPath. 我有一个名为config的类,其中有两个名为key paramValue和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). 当我应用该类的ChooseType方法时,该方法必须返回一种不同类型(Int或bool或String)的变量paramValue。
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. 我的问题是如何访问ConfigValue类中的PolimorphProperty方法,以检索示例paramValue Int类型。
Having both T
and RetType
is redundant. 同时拥有T
和RetType
是多余的。 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>()
. 像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));
}
}
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>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.