最近在做research项目,和高手学了不少东西。。呵呵,分享一下。。 在返回值不确定的情况下使用范型。。
Convert.ChangeType 方法 (Object, Type)
返回具有指定 Type 而且其值等效于指定对象的object。
Code
public static class TestGenerics
{
public static T GetValue<T>(string name)
{
string xPath ="//setting[@name=\"" + name + "\"]";
XmlNode node = doc.SelectSingleNode(xPath);
if (node != null)
return (T)Convert.ChangeType(node.Attributes["value"].Value, typeof(T));
else
{
T value = default(T);
if (typeof(T)==typeof(string))
value = (T)Convert.ChangeType(string.Empty, typeof(T));
return value;
}
}
}
public static class TestGenerics
{
public static T GetValue<T>(string name)
{
string xPath ="//setting[@name=\"" + name + "\"]";
XmlNode node = doc.SelectSingleNode(xPath);
if (node != null)
return (T)Convert.ChangeType(node.Attributes["value"].Value, typeof(T));
else
{
T value = default(T);
if (typeof(T)==typeof(string))
value = (T)Convert.ChangeType(string.Empty, typeof(T));
return value;
}
}
}
在调用的地方:
this
.txtNum1.Value
=
TestGenerics.GetValue
<
int
>
(
"
Num1
"
);
this .txtNum2.Value = TestGenerics.GetValue < int > ( " Num2 " );
this .txtNum2.Value = TestGenerics.GetValue < int > ( " Num2 " );
之后还会努力研究。。多多学习。。
哈哈。。。 激情成就未来。。