我有一个具有唯一键的对象集合。该键可以是数字或字符串,它是通用的,大多数班级并不关心它,因为它存储在
Dictionary<TKey, TItem>
中。
现在该类应该提供一个方法来为要添加的项目返回新的唯一键。这就是我找不到解决方案的地方。我尝试阅读 C# 的新通用方法功能,但这对我来说没有任何意义。
我正在寻找类似下面的 GetUniqueKey 方法的方法:
// Restrict TKey to numbers or strings: https://stackoverflow.com/a/30660880
class MyCollection<TKey, TObject>
where TObject : class
where TKey : notnull, IComparable, IConvertible, IEquatable<TKey>
{
private Dictionary<TKey, TObject> items;
public TKey GetUniqueKey()
{
if (TKey is INumber)
return items.Keys.Max() + 1;
if (TKey is string)
return Guid.NewGuid().ToString();
throw new NotSupportedException("Key type not supported.");
}
}
这完全可以做到吗?
您确实可以在这里使用通用数学 API,但您仍然需要某种方法来说服编译器
TKey
是一个数字。对于 string
的情况,您只需检查 typeof(TKey) == typeof(string)
并进行一些转换即可。
这是一个通过
dynamic
联合绑定到辅助方法来执行此操作的示例:
私人词典
public TKey GetUniqueKey()
{
if (typeof(TKey).GetInterface("System.Numerics.INumber`1") != null)
return GetNumericUniqueKey((dynamic)items.Keys);
if (typeof(TKey) == typeof(string))
return (TKey)(object)Guid.NewGuid().ToString();
throw new NotSupportedException("Key type not supported.");
}
private static T GetNumericUniqueKey<T>(ICollection<T> existingKeys) where T: INumber<T> {
if (existingKeys.Any()) {
return (existingKeys.Max() ?? T.Zero) + T.One;
}
return T.Zero;
}