在C#中使用`where T:SOMETHING`构造

时间:2022-12-30 20:54:02

Just found a bit of code someone here had written to access some DB Entities...

刚刚找到一些代码,有人在这里编写了访问某些数据库实体的代码......

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

Theres just something about it that doesn't seem very generic. The fact that the sprocs are passed into the inner method feels ugly. but the only way I can see around that is to have an if/else in the private method along the lines of

只是它的一些东西似乎不是很通用。将sprocs传递到内部方法的事实感觉很难看。但我能看到的唯一方法是在私有方法中使用if / else

if(type == int)
    sproc = "GetByID";
else if (type == Guid)
    sproc = "GetByGUID";

Also the exception throwing looks ugly as well... is there anyway to use a where T : clause

此外抛出的异常看起来也很丑......无论如何都要使用where T:子句

e.g.

private static OurCustomObject<T>(T identifier) where T : int OR Guid

Any suggestions on how to clean this up a little.

有关如何清理这一点的任何建议。

4 个解决方案

#1


You can't specify a constraint which says "it's one of these two", no.

你不能指定一个约束,说“这是这两个中的一个”,不。

What you could do is:

你能做的是:

Dictionary<Type, string> StoredProcedureByType = new Dictionary<Type, string>
{
    { typeof(Guid), "GetByGUID" },
    { typeof(int), "GetByID" }
};

Then use:

string sproc;
if (!StoredProcedureByType.TryGetValue(typeof(T), out sproc))
{
    throw new ArgumentException("Invalid type: " + typeof(T).Name);
}

This is probably overkill for just a couple of types, but it scales well if you have a lot of types involved.

这对于几种类型来说可能有些过分,但如果你涉及很多类型,它可以很好地扩展。

Given that both types are value types, you can make it a bit more robust with a constraint of:

鉴于这两种类型都是值类型,您可以通过以下约束使其更加健壮:

where T : struct

but that will still allow byte etc.

但这仍然允许字节等

#2


The code you provided looks reasonably fine to me, because private static OurCustomObject<T>(T identifier, string sproc) is private. I would even drop the exception checking from this method, because again - its private, so this class controls what gets passed to the method. The if statement would be rather horrible and over-engineered.

你提供的代码看起来相当不错,因为私有静态OurCustomObject (T标识符,字符串sproc)是私有的。我甚至会从这个方法中删除异常检查,因为再次 - 它是私有的,所以这个类控制传递给方法的内容。 if语句会相当可怕并且过度设计。

#3


The neatest thing to do is probably doing something like this:

最重要的事情可能就是这样做:

public interface IPrimaryKey 
{
}

public class PrimaryGuidKey(Guid key) : IPrimaryKey 

public class PrimaryIntegerKey(int key) : IPrimaryKey

private static OurCustomObject<T>(T identifier) where T : IPrimaryKey

#4


There is no support for such a where clause to limit the type parameter in that way (unfortunatelly).

不支持这样的where子句以这种方式限制类型参数(不幸的是)。

In this case, you might find that passing identifier as an object, and not using generics is actually cleaner (when I needed something similar, that is what I ended up doing: seemed to be the least worst approach).

在这种情况下,您可能会发现将标识符作为对象传递而不使用泛型实际上更清晰(当我需要类似的东西时,这就是我最终做的事情:似乎是最差的方法)。

This is an area that C# is weak, being neither a dynamic language or being able to specialise the template (C++ like, only providing implementations for T = int and T = Guid).

这是一个C#弱的领域,既不是动态语言,也不能专门化模板(C ++就像只提供T = int和T = Guid的实现)。

Adendum: In this case I would likely stick with the overload, but change the type check to an Assert as that is a private helper method.

Adendum:在这种情况下,我可能会坚持使用重载,但是将类型检查更改为Assert,因为这是一个私有帮助器方法。

#1


You can't specify a constraint which says "it's one of these two", no.

你不能指定一个约束,说“这是这两个中的一个”,不。

What you could do is:

你能做的是:

Dictionary<Type, string> StoredProcedureByType = new Dictionary<Type, string>
{
    { typeof(Guid), "GetByGUID" },
    { typeof(int), "GetByID" }
};

Then use:

string sproc;
if (!StoredProcedureByType.TryGetValue(typeof(T), out sproc))
{
    throw new ArgumentException("Invalid type: " + typeof(T).Name);
}

This is probably overkill for just a couple of types, but it scales well if you have a lot of types involved.

这对于几种类型来说可能有些过分,但如果你涉及很多类型,它可以很好地扩展。

Given that both types are value types, you can make it a bit more robust with a constraint of:

鉴于这两种类型都是值类型,您可以通过以下约束使其更加健壮:

where T : struct

but that will still allow byte etc.

但这仍然允许字节等

#2


The code you provided looks reasonably fine to me, because private static OurCustomObject<T>(T identifier, string sproc) is private. I would even drop the exception checking from this method, because again - its private, so this class controls what gets passed to the method. The if statement would be rather horrible and over-engineered.

你提供的代码看起来相当不错,因为私有静态OurCustomObject (T标识符,字符串sproc)是私有的。我甚至会从这个方法中删除异常检查,因为再次 - 它是私有的,所以这个类控制传递给方法的内容。 if语句会相当可怕并且过度设计。

#3


The neatest thing to do is probably doing something like this:

最重要的事情可能就是这样做:

public interface IPrimaryKey 
{
}

public class PrimaryGuidKey(Guid key) : IPrimaryKey 

public class PrimaryIntegerKey(int key) : IPrimaryKey

private static OurCustomObject<T>(T identifier) where T : IPrimaryKey

#4


There is no support for such a where clause to limit the type parameter in that way (unfortunatelly).

不支持这样的where子句以这种方式限制类型参数(不幸的是)。

In this case, you might find that passing identifier as an object, and not using generics is actually cleaner (when I needed something similar, that is what I ended up doing: seemed to be the least worst approach).

在这种情况下,您可能会发现将标识符作为对象传递而不使用泛型实际上更清晰(当我需要类似的东西时,这就是我最终做的事情:似乎是最差的方法)。

This is an area that C# is weak, being neither a dynamic language or being able to specialise the template (C++ like, only providing implementations for T = int and T = Guid).

这是一个C#弱的领域,既不是动态语言,也不能专门化模板(C ++就像只提供T = int和T = Guid的实现)。

Adendum: In this case I would likely stick with the overload, but change the type check to an Assert as that is a private helper method.

Adendum:在这种情况下,我可能会坚持使用重载,但是将类型检查更改为Assert,因为这是一个私有帮助器方法。