通用铸造 [英] Generic Casting
本文介绍了通用铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我怀疑答案是否定的,但可以在C#.NET(v2.0)中做这样的事情。
class Converter< E>
{
public E Make(object o)
{
return o as E;
$ b如果不是,是否可以检查这种类型:
public bool IsType(object o,Type t)
{
return o is E;
}
我对术语不太肯定,所以Google很难我。
但我的猜测是这两个问题是相关的。任何想法?
解决方案 您可以将 o
转换为 E
使用 () Operator :
class Converter< E>
{
public E Make(object o)
{
return(E)o;如果你使用
$ b $ /msdn.microsoft.com/en-us/library/cscsdfbt.aspxrel =nofollow> as , o作为E $ c $因为如果 o
不能转换为,那么c>要求 E
E
,结果是(E)null
。您可以通过使用限制 E
引用类型 = nofollow> class 约束:
class Converter< E> E:class
{
public E Make(object o)
{
return o as E;
public bool IsType(object o,Type t)
{
return(o!= null)? t.IsAssignableFrom(o.GetType()):t.IsClass;
}
I suspect the answer is no, but is it possible to do something like this in C#.NET (v2.0).
class Converter<E>
{
public E Make(object o)
{
return o as E;
}
}
If not, is it possible to check types like this:
public bool IsType(object o, Type t)
{
return o is E;
}
I'm not certain about the terminology so it is rather hard to Google for me.
But my guess is that these two problems are related. Any ideas?
解决方案 You can cast o
to E
using the () Operator:
class Converter<E>
{
public E Make(object o)
{
return (E)o;
}
}
If you use as, o as E
requires E
to a be a reference type, because if o
is not castable to E
, the result is (E)null
. You can constrain E
to reference types by using the class Constraint:
class Converter<E> where E : class
{
public E Make(object o)
{
return o as E;
}
}
public bool IsType(object o, Type t)
{
return (o != null) ? t.IsAssignableFrom(o.GetType()) : t.IsClass;
}
这篇关于通用铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文