刚刚发现这里有人编写的一些代码来访问一些数据库实体...
public static OurCustomObject GetOurCustomObject(int primaryKey)
{
return GetOurCustomObject<int>(primaryKey, "usp_GetOurCustomObjectByID");
}
public static OurCustomObject GetOurCustomObject(Guid uniqueIdent)
{
return GetOurCustomObject<Guid>(uniqueIdent, "usp_GetOurCustomObjectByGUID");
}
private static OurCustomObject<T>(T identifier, string sproc)
{
if((T != typeof(int)) && (T == typeof(Guid)))
{
throw new ArgumentException("Identifier must be a string or an int");
}
//ADO.NET Code to make DB Call with supplied sproc.
}
它只是有些东西看起来不太通用
。事实上
将存储过程传递到内部方法感觉很丑陋。但我能看到的唯一方法是按照
if(type == int)
sproc = "GetByID";
else if (type == Guid)
sproc = "GetByGUID";
此外,抛出的异常看起来也很丑陋......无论如何都可以使用 where T : 子句
例如
private static OurCustomObject<T>(T identifier) where T : int OR Guid
关于如何稍微清理一下的任何建议。
最佳答案
你不能指定一个约束说“它是这两个之一”,不。
您可以做的是:
Dictionary<Type, string> StoredProcedureByType = new Dictionary<Type, string>
{
{ typeof(Guid), "GetByGUID" },
{ typeof(int), "GetByID" }
};
然后使用:
string sproc;
if (!StoredProcedureByType.TryGetValue(typeof(T), out sproc))
{
throw new ArgumentException("Invalid type: " + typeof(T).Name);
}
这对于几个类型来说可能有点矫枉过正,但如果涉及到很多类型,它的扩展性会很好。
鉴于这两种类型都是值类型,您可以通过以下约束使它位更健壮:
where T : struct
但这仍然允许 byte
等
关于c# - 在 C# 中使用 `where T : SOMETHING` 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/949627/