简体   繁体   中英

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

In the file that both interfaces are in, add a using alias directive like this:

using UserIdType = System.String;

Now, you can use UserIdType instead of String in both User and IUserService . 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 .


However, wouldn't you still have to change the code that depends on the Id property? Changing one extra thing isn't that much of a trouble, compared to all the other code changes you'll have to make.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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