如何做到在C#模板特殊化 [英] How to do template specialization in C#
问题描述
你怎么会做在C#专业化?
我会构成问题。你有一个模板类型,你不知道它是什么。但是,你知道如果从XYZ派生您要拨打.alternativeFunc()。一个伟大的方式是调用一个专门的函数或类,并有normalCall返回.normalFunc(),而有其他的专业化上的任何派生类型XYZ的调用.alternativeFunc()。这将如何在C#做什么?
How would you do specialization in C#? I'll pose a problem. You have a template type, you have no idea what it is. But you do know if its derived from XYZ you want to call .alternativeFunc(). A great way is to call a specialized function or class and have normalCall return .normalFunc() while have the other specialization on any derived type of XYZ to call .alternativeFunc(). How would this be done in C#?
推荐答案
在C#中,最接近专业化是使用更具体的超载;然而,这是脆性的,并且不包括每一种可能的使用情况。例如:
In C#, the closest to specialization is to use a more-specific overload; however, this is brittle, and doesn't cover every possible usage. For example:
void Foo<T>(T value) {Console.WriteLine("General method");}
void Foo(Bar value) {Console.WriteLine("Specialized method");}
下面,如果编译器知道类型在编译,它会选择最具体的
Here, if the compiler knows the types at compile, it will pick the most specific:
Bar bar = new Bar();
Foo(bar); // uses the specialized method
不过....
void Test<TSomething>(TSomething value) {
Foo(value);
}
将使用美孚&LT; T&GT;
甚至 TSomething =酒吧
,因为这是在编译时烧毁
will use Foo<T>
even for TSomething=Bar
, as this is burned in at compile-time.
另外一个方法是使用型测试的内的一个通用方法 - 然而,这通常是一个差的想法,并且是不建议
One other approach is to use type-testing within a generic method - however, this is usually a poor idea, and isn't recommended.
基本上,C#只是不希望你用专业的工作,除了多态性:
Basically, C# just doesn't want you to work with specializations, except for polymorphism:
class SomeBase { public virtual void Foo() {...}}
class Bar : SomeBase { public override void Foo() {...}}
下面 Bar.Foo
将始终解析到正确的覆盖。
Here Bar.Foo
will always resolve to the correct override.
这篇关于如何做到在C#模板特殊化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!