简体   繁体   English

有没有办法将泛型参数类型限制为某个属性的类型?

[英]Is there a way to constrain a generic parameter type to the type of a certain property?

Please consider the following code:请考虑以下代码:

public class User 
{
  public String Id {get; set;}
}

public interface IUserService 
{
  bool IsAdmin(string userId);
}

I would like to not specify the type of the userId parameter in the interface but rather use a generic type that is constrained to be of the same type as the property Id in the class User so that I don't have to change the code if I eventually decide to change the type of the property.我不想在接口中指定userId参数的类型,而是使用一个泛型类型,该类型被限制为与类User的属性Id具有相同的类型,这样我就不必更改代码,如果我最终决定更改属性的类型。 So what I have in mind is something like:所以我想到的是:

public interface IUserService 
{
  bool IsAdmin<T>(T userId) where T : typeof(User.String)
}

Is that possible?那可能吗?

No, that's not possible.不,那是不可能的。 It's also not very useful to have a generic constrained to one specific type, that defeats the purpose of having a generic.将泛型限制为一种特定类型也不是很有用,这违背了拥有泛型的目的。

What you could do is make your own type UserId (class or maybe struct) and use that in both places.您可以做的是创建自己的类型UserId (类或结构)并在两个地方使用它。 So if your structure of what a user identifier is in your program changes, you can change it in one place and it works all over your program.所以,如果你对什么样的用户标识符程序中的更改结构,你可以在一个地方改变它,它工作在你的计划。

也许您可以使用动态属性?:

public dynamic Id { get; set; }

Currently, this isn't possible, but as a workaround, you can use a using alias directive , provided that both interfaces are in the same file.目前,这是不可能的,但作为一种解决方法,您可以使用using alias 指令,前提是两个接口都在同一个文件中。

In the file that both interfaces are in, add a using alias directive like this:在两个接口所在的文件中,添加一个 using alias 指令,如下所示:

using UserIdType = System.String;

Now, you can use UserIdType instead of String in both User and IUserService .现在,您可以在UserIUserService使用UserIdType而不是String When you want to change the type of the Id property, just change the using alias directive, and you don't have to change the types of either Id or the parameter userId .当您想更改Id属性的类型时,只需更改 using alias 指令,而不必更改Id或参数userId的类型。


However, wouldn't you still have to change the code that depends on the Id property?但是,您是否仍然需要更改依赖于Id属性的代码? Changing one extra thing isn't that much of a trouble, compared to all the other code changes you'll have to make.与您必须进行的所有其他代码更改相比,更改一件额外的事情并没有那么麻烦。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM