[英]How do I use a generic type within a a method that has not specified the type in the signature
[英]How do to implement type specified generic method?
我有MyClass<T> where T : IComparable
类MyClass<T> where T : IComparable
,我想实现一个在T
为String
将被调用的方法。 我怎样才能做到这一点?
现在我有以下代码:
public void Method()
{
...
Type typeParameterType = typeof(T);
if (typeParameterType.Equals(typeof(String)))
{
// here I can't do (String) anyTTypeValue
// to call handleString(String) method
}
...
}
您可以利用as
运算符的优势,并检查valString
是否不为null。 然后,您将有权访问特定于string
属性和方法。 下一个代码段将显示主要思想:
public void Method<T>(T val)
{
string valString = val as string;
if(valString != null)
{
Console.WriteLine (valString.Length);
}
}
Method("tyto"); //prints 4
Method(5); //prints nothing
尝试:
(string)(object) anyTypeValue;
顺便说一句,您不必做所有的事情-您可以说:
if(anyTypeValue is string)
{
string strValue = (string)(object)anyTypeValue;
...
}
编辑:
如@Ilya所建议,您可以在引用类型和Nullable<T>
类型的情况下使用as
。 由于string
是引用类型,因此可以执行以下操作:
var strValue = anyTypeValue as string;
if(strValue != null)
{
...
}
但是,您不能使用int
做同样的事情:
var intValue = anyTypeValue as int; //compiler error
还要注意,由于anyTypeValue
为null
或anyTypeValue
不是string ,因此无法确定strValue != null
是否为false。
在某些用例中,这些都不是问题,因此最好使用as
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.