猿问

用通用扩展方法替换继承

我创建了一个继承KeyedByTypeCollection并扩展它的类。


https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.keyedbytypecollection-1?view=netframework-4.7.2


KeyedByTypeCollection只有在没有找到项目Find时返回的方法。null我更喜欢一种TryGetValue方法,所以我添加了一个。


internal class TypeCollection<V> : KeyedByTypeCollection<V>

{

    public T ValueOrDefault<T>() where T : V

    {

        if (!Contains(typeof(T)))

        {

            return default(T);

        }


        return (T)this[typeof(T)];

    }


    public bool TryGetValue<T>(out T value) where T : V

    {

        if (!Contains(typeof(T)))

        {

            value = default(T);

            return false;

        }


        value = (T)this[typeof(T)];

        return true;

    }

}

问题是没有继承的理由。我只想扩展一个现有的类。我从这两种扩展方法开始


internal static class KeyedByTypeCollectionExtensions

{

    public static T ValueOrDefault<T>(this KeyedByTypeCollection<V> collection) where T : V

    {

        if (!collection.Contains(typeof(T)))

        {

            return default(T);

        }


        return (T)collection[typeof(T)];

    }


    public static bool TryGetValue<T>(this KeyedByTypeCollection<V> collection, out T value) where T : V

    {

        if (!collection.Contains(typeof(T)))

        {

            value = default(T);

            return false;

        }


        value = (T)collection[typeof(T)];

        return true;

    }

}

但是如何设置这些扩展方法?我必须为泛型类型设置V什么?


人到中年有点甜
浏览 103回答 1
1回答

森林海

您将必须定义V.public static T ValueOrDefault<T,V>(this KeyedByTypeCollection<V> collection) where T : V和public static bool TryGetValue<T,V>(this KeyedByTypeCollection<V> collection, out T value)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;where T : V它可以很好地使用TryGetValue,因为编译器会知道使用了哪些类型,但是对于 ,ValueOrDefault您必须设置这两种类型,这有点难看。让我们考虑以下类:public class A { }public class B : A { }那么用法可以是:var myCollection = new KeyedByTypeCollection<A>();myCollection.Add(new A());myCollection.Add(new B());myCollection.TryGetValue(out B b); // <-- Nice! :)b = myCollection.ValueOrDefault<B,A>();&nbsp; // <-- Ugly :(
随时随地看视频慕课网APP
我要回答