什么是Java通配符的C#泛型相当于 [英] What is the equivalent of Java wildcards in C# generics

查看:104
本文介绍了什么是Java通配符的C#泛型相当于的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个应用程序,我需要调用一个泛型类的方法,我不关心实例实际类型。类似下面的Java code:

I'm developing an application where I the need to invoke a method of a generic class and I don't care about the instances actual type. Something like the following Java code:

public class Item<T>{
  private T item;

  public doSomething(){...}
}

...
public void processItems(Item<?>[] items){
 for(Item<?> item : items)
   item.doSomething();
}

当时我是在赶时间,所以我通过定义与我需要调用的方法的接口解决我的问题,并提出了通用类实现它。

At the time I was on a hurry, so I solved my problem by defining a interface with the methods I needed to invoke and made the generic class implement it.

public interface IItem  
{
   void doSomething();
}

public class Item<T> : IItem {
  private T item;

  public void doSomething(){...}
}

...
public void processItems(IItem[] items)
{
 foreach(IItem item in items)
   item.doSomething();
}

这个解决办法工作正常,但我想知道什么是要实现相同的行为的正确方法。

This workaround works fine, but I'd like to know what is the correct way to achieve the same behavior.

编辑:

我忘了提及的 processItems 的调用者不知道实际的类型。其实当时的想法是,该数组作为参数传递给 processItems 通过可能包含混合类型。自不可能有在.net这样的一个数组,使用非通用基类或接口似乎是唯一的出路。

I forgot to refer that the caller of processItems doesn't know the actual types. Actually the idea was that the array passed as argument to processItems could contain intermixed types. Since its not possible to have such an array in .Net, using a non generic base class or interface seems to be the only way.

推荐答案

正常的方式做,这将是使该方法一般:

The normal way to do this would be to make the method generic:

public void ProcessItems<T>(Item<T>[] items) {
  foreach(Item<T> item in items)
    item.DoSomething();
}

假设的主叫的知道的类型,类型推断应该意味着他们没有显式指定它。例如:

Assuming the caller knows the type, type inference should mean that they don't have to explicitly specify it. For example:

Item<int> items = new Item<int>(); // And then populate...
processor.ProcessItems(items);

说了这么多,创造了非通用接口指定类型无关的操作可能是有用的为好。这将在很大程度上取决于你的具体使用案例。

Having said that, creating a non-generic interface specifying the type-agnostic operations can be useful as well. It will very much depend on your exact use case.

这篇关于什么是Java通配符的C#泛型相当于的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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