我创建了一个继承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什么?
森林海
相关分类