在这里使用通用更好,还是界面足够?

时间:2011-02-02 21:39:06

标签: c# interface generics

使用第一种基于泛型的方法而不是简单地使用接口的第二种方法是否有任何优势?

class MyClass
{
    public static void Method<T>(T t) where T:IBar
    {            
    }

    public static void Method(IBar bar)
    {
    }
}

3 个答案:

答案 0 :(得分:2)

就个人而言,我认为在这种特殊情况下使用泛型没有任何优势。

答案 1 :(得分:1)

在这种情况下,将接口类型作为约束是没有用的。

但有时它是,例如:

interface IHasId
{
   public int Id { get; }
}

public static IList<int> GetIds<T>(IList<T> items) where T:IHasId
{            
    return items.Select(item => item.Id).ToList();
}

在这个(非常愚蠢)的情况下,你可以在非通用情况下传递IList<IHasIdImplementation>,你必须通过IList<IHasId>

答案 2 :(得分:0)

我发现有两种情况我需要在方法定义中使用泛型。

第一种情况是需要通用类型值指定返回值。所以当它像:

public T Method1<T>(object someobject) where T:IBar;

第二种情况是您需要在方法内使用type参数(而不仅仅是接口)。

两个要求的示例是ViewModelFactory类中的GetModelByKey()方法。此类通过ViewModelType和KeyType缓存ViewModel,结果方法如下所示:

public ViewModelType GetViewModelByKey<ViewModelType, KeyType>(KeyType key) 
        where ViewModelType : ViewModelBase, new()
    {
        IDictionary dictionary;
        var type = typeof(ViewModelType);
        if (!keyedViewModelDictionaries.TryGetValue(type, out dictionary))
        {
            dictionary = new Dictionary<KeyType, ViewModelType>();
            keyedViewModelDictionaries.Add(type, dictionary);
        }
        var viewModels = (Dictionary<KeyType, ViewModelType>)dictionary;
        ViewModelType vm;
        if (!viewModels.TryGetValue(key, out vm))
        {
            vm = new ViewModelType();
            vm.Initialize(this);
            viewModels.Add(key, vm);
        }
        return vm;
    }
相关问题