c# - 在 C# 中使用 `where T : SOMETHING` 结构

标签 c# generics

刚刚发现这里有人编写的一些代码来访问一些数据库实体...

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.
}

它只是有些东西看起来不太通用。事实上 将存储过程传递到内部方法感觉很丑陋。但我能看到的唯一方法是按照

的方式在私有(private)方法中使用 if/else
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/

相关文章:

java - 将已转换的对象返回到具体类类型

java - 在java中将泛型类型作为参数传递?

c# - 在 C# 中使用 WebClient.DownloadString 发送 POST

c# - Windows Media Player 视频无缝循环

c# - 将 Jar 嵌入到 C# 表单中

c# - (open generic type) 没有指定参数的 typeof 泛型类型

c# - 如果 A<T1,T2> 是实际类型的模板,那么为什么允许 typeof(A<,>) ?

java - 从 Set<Type> 到 Set<Type B>

c# - 为什么没有捕获的 lambda 从 C# 5 中的静态方法更改为 C# 6 中的实例方法?

c# - 反射测试未显示预期数字