设置无类型静态方法在泛型类 [英] Set no type for a static method in a generic class

查看:138
本文介绍了设置无类型静态方法在泛型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是Java的粉丝,但Java允许不是一般类,并在这种情况下,它的威胁类型对象设置类型键入。不过,据我所知,C#强制设定<的类型; T>随时泛型类已被实例化或简单来说使用。然而,让我们说,我们有一个通用类,我们需要在那里一个静态方法,它不依赖于<的类型; T>

Not a fan of Java, but Java allows not setting types for generic classes and in that case it threats the type as Object type. However, as far as I know, C# enforces setting the type of <T> anytime the generic class has to be instantiated or simply speaking used. However, let's say that we have a generic class, and we need a static method in there which does not rely on the type of <T>.

首先,我们知道,它可以移动到一个单独的上下文,或者我们可以设置一个虚拟的类型<的; T> ,但作为一个编程的难题有没有办法来调用它的没有定义 T 的类型?

Firstly, we know that it can be moved to a separate context or we can set a dummy type of <T>, but as a programming puzzle is there any way to call it Without defining the type of T?

例如:

 class Test<T> where T: ITestable {
     ...
     public static void CreateTestFile(String fileName) {...}
 }
 Test.CreateTestFile("test.txt");

这是可以做到的Java,显然不能在C#。但我只是想确认一下。

This can be done Java and apparently can't be in C#. But I just wanna make sure.

推荐答案

Java和C#实现泛型是不同的:

Java and C# implement generics differently:


  • Java使用的类型擦除的,这基本上意味着,在编译的时候,任何事情你把< T> 擦除并成为对象东西<富> 东西<酒吧GT; 将在运行时相同的类型,以及西港岛线是有效等于东西<对象>

  • Java uses type erasure, which basically means that at compile time, anything you put in <T> is erased and becomes Object. Something<Foo> and Something<Bar> will be the same type at runtime, and wil be effectively equal to Something<Object>.

C#使用的运行时物化的,意义对于每次与不同的 T 使用类型,运行时完全生成一个新的类,通过使用开放式泛型版本作为模板(这意味着它也产生了底层的本地每一次 T 正如你所说的话)的代码。 东西<富> 东西<酒吧方式> 是两个不相关的类型至于CLR而言

C# uses run-time reification, meaning that for each type you use with a distinct T, the runtime generates a new class altogether, by using the open generic version as a template (which means it also generates the underlying native code once per T as you call it). Something<Foo> and Something<Bar> are two unrelated types as far as the CLR is concerned.

希望你明白,为什么这种差异对你的情况很重要。忽略 T 在Java小事,但在C#中不那么容易了。

Hopefully you understand why this difference is important to your scenario. Ignoring T is trivial in Java, but not so easy in C#.

如果您不需要 T 在你的代码,然后使用非泛型方法:

If you don't need T in your code, then use a non-generic method:

abstract class Test
{
    public static void CreateTestFile(String fileName) {...}
}

class Test<T> : Test
    where T : ITestable
{
     ...
}

下面,那最好不过了:)

Here, that's better :)

此外,请注意实例方法,你可以使用的的和的逆变的接口松动在编译时为一个已知 T 的要求。例如,如果您使用的是协变的界面,你只需要知道 T 的基本类型。

Also, note that for instance methods, you can use covariant and contravariant interfaces to loosen the requirement for a known T at compile-time. For instance, if you use a covariant interface, you only need to know a base type of T.

这篇关于设置无类型静态方法在泛型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆