【问题标题】:What is the workaround for the missing C# generic wildcards <?> [duplicate]缺少 C# 通用通配符 <?> 的解决方法是什么 [重复]
【发布时间】:2013-11-26 16:54:45
【问题描述】:

在 Java 中,我可以声明如下方法:public boolean doSth(Cache&lt;?&gt; cache, CacheItem item){...}

public interface Cache<T> {
    public boolean Contains(T item);
}

public class CacheFilePath implements Cache<FilePathItem> {
    @Override
    public boolean Contains(FilePathItem item) {
        return false; // TODO
    }
}

public class ItemHandler {

    public boolean doSth(Cache<?> cache, CacheItem item){
        if(cache instanceof CacheHostName && item instanceof HostNameItem){
            CacheHostName c = (CacheHostName) cache;
            HostNameItem i = (HostNameItem) item;
            return check(c, i);
        }
        else if(cache instanceof CacheFilePath && item instanceof FilePathItem){
            CacheFilePath c = (CacheFilePath) cache;
            FilePathItem i = (FilePathItem) item;
            return check(c, i);
        }
        throw new RuntimeException("Invalid arguments  !!!");
    }

    private boolean check(Cache<HostNameItem> cache, HostNameItem item){
        return cache.Contains(item);
    }

    private boolean check(Cache<FilePathItem> cache, FilePathItem item){
        return cache.Contains(item);
    }
}

如何在 C# 中声明这样的方法?

【问题讨论】:

  • 如何使方法通用不能解决您的问题?旁注,通常是代码气味使方法通用,然后只需切换一堆可能的派生类型并对其进行操作。通常情况下,您应该只拥有 N 个重载,而不是一堆类型检查和强制转换。
  • 这个问题通常可以通过实现使用object的接口的泛型类以及使用特定类型的相同方法来避免。如果Cache&lt;&gt; 不这样做并且它不是你的修改,你可以得到最接近上述代码的是接受object 并手动输入检查typeof(Cache&lt;&gt;)

标签: c# .net generics wildcard


【解决方案1】:

你可以像这样在方法上声明一个类型参数:

public boolean doSth<T>(Cache<T> cache, CacheItem item){
    ...
}

或者使用非泛型基类或接口:

public interface ICache { ... }
public class Cache<T> : ICache { ... }

public boolean doSth(ICache cache, CacheItem item){
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2014-10-31
    • 1970-01-01
    相关资源
    最近更新 更多