我创建了一个继承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 :(
- 1 回答
- 0 关注
- 102 浏览
添加回答
举报
0/150
提交
取消