为了账号安全,请及时绑定邮箱和手机立即绑定

用通用扩展方法替换继承

用通用扩展方法替换继承

C#
人到中年有点甜 2022-06-12 15:20:06
我创建了一个继承KeyedByTypeCollection并扩展它的类。https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.keyedbytypecollection-1?view=netframework-4.7.2KeyedByTypeCollection只有在没有找到项目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什么?
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您将必须定义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) 

       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>();  // <-- Ugly :(


查看完整回答
反对 回复 2022-06-12
  • 1 回答
  • 0 关注
  • 102 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号