简体   繁体   English

返回不同泛型集合的泛型方法

[英]Generic Method returning different generic collections

Hi I have a Method like this: 嗨我有这样的方法:

        public T LoadR<T, K>()
        where T : ObservableCollection<K>, new()
        where K : IStoreElement, new() {
        T onC = new T();
        //....
        return (onC);
    }

Further I have a class XObservableCollection which derivies from ObservableCollection. 此外,我有一个XObservableCollection类,它派生自ObservableCollection。 It works as it is when I call: 当我打电话时,它的工作原理是:

Categories = LoadR<ObservableCollection<Category>,Category>();
Products = LoadR<XObservableCollection<Product>,Product>();

What I want to do is to make a call like this (avoid passing the K as extra parameter): 我想要做的就是这样做一个调用(避免将K作为额外参数传递):

Categories = LoadR<ObservableCollection<Category>>();
Products = LoadR<XObservableCollection<Product>>();

I know that I could write an extension for it. 我知道我可以为它写一个扩展名。 But I curious if there is a way to achive this without it. 但我很好奇是否有办法在没有它的情况下实现这一目标。

Manfred 曼弗雷德

I don't think you can. 我认为你不能。

C# has a mechanism to understand generic agruments from method paramaters when used in it, but not from other generic arguments of the same method. C#有一种机制来理解方法参数中使用的泛型agruments,而不是来自同一方法的其他泛型参数。 It doesn't work. 它不起作用。

Maybe you can change your signature to: 也许您可以将签名更改为:

    private static ObservableCollection<K> LoadR<K>(.ObservableCollection<K> onC)
        where K : IStoreElement, new()
    {
        //....
        return onC;
    }

Usage would be: 用法是:

    static void TestLoad()
    {
        var result1 = LoadR(new ObservableCollection<Something>());
        var result2 = LoadR(new DerivedClassFromObservableCollection<Something>());
    }

Which I agree is not that good, and I can se it's not what you are looking for. 我同意的不是那么好,我可以认为它不是你想要的。

But just because C# wouldn't let you try to infer the types from the generic arguments. 但只是因为C# 不会让你尝试从泛型参数中推断出类型。

..... .....

The other way aroudn is to make it use a specific collection. 另一种方式是使它使用特定的集合。 I can see you don't want this even more. 我可以看到你不想要这个。

So, one thing you can do is make it return IEnumerable instead, then you usage will be something like: 所以,你可以做的一件事是让它返回IEnumerable,然后你的用法将是这样的:

    static void TestLoad()
    {
        var result1 = new ObservableCollection( LoadR<Something>() );
        var result1 = new DerivedClassFromObservableCollection( LoadR<Something>() );
    }

Which may not be good also if you want to do fancy things with the collection itself, because you no-longer own it. 如果你想用收藏本身做一些奇特的东西,那也许不好,因为你不再拥有它。

.... ....

I would go for the very first option myself. 我自己会选择第一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM