C# generic interface specialization

前端 未结 6 1756
自闭症患者
自闭症患者 2020-12-10 02:42

I wonder if it is in any way possible to specialize generic interface methods somehow in C#? I have found similar questions, but nothing exactly like this. Now I suspect tha

6条回答
  •  盖世英雄少女心
    2020-12-10 03:36

    Because C# generics are runtime templates in some circumstances you should use runtime specialization. For example, in generic static methods, inheritance and interfaces aren't usable. If you want to specialize generic static methods - in particular extension methods - you have to detect the type in code with constructs like :

    if (typeof(T)==typeof(bool))

    For specialization of reference types (like string for example), and an argument T data, you would prefere:

    string s = data as string; if (s!=null)

    In this example, a problem come from conversion between T and bool in specialized code : You know that T is bool but the language doesn't allow conversion between those types. The solution come from the object type: an object can be casted to any type (conversion is checked at runtime and not at compile time in this case). so if you have

    T data;

    you can write:

    bool b=(bool)(object)data; data=(T)(object)b;

    This isn't perfect: If type equality is quite fast, in some circumstances you have to test if T is a derived type of a specified type (a little longer). And when T is a value type like bool, cast to object and then back to type mean value type boxing/unboxing and runtime type check for reference types. Runtime optimiser can remove these non necessary steps but I cannot say if they do so.

    Depending on the usage of your static method, remember that you can apply where T: ... restrictions on parametrized types. And that default(T) return false for boolean, zero for numeric base types and null for reference types.

    Runtime specialization implies an additional test steps and boxing/unboxing/runtime type checks, so it isn't the panacea but allows too specialize generic methods in an acceptable time in many circumstances: For long operation (in particular for optimization) or when hiding or grouping of types complexity management is more important than performances.

提交回复
热议问题