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

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

请考虑以下代码:

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

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

我不想在接口中指定 userId 参数的类型,而是使用被限制为与 属性 [=14= 相同类型的泛型类型] 在 class User 中,以便在我最终决定更改 属性 的类型时不必更改代码。 所以我的想法是:

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

这可能吗?

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

public dynamic Id { get; set; }

不,那不可能。将泛型限制为一种特定类型也不是很有用,这违背了拥有泛型的目的。

您可以做的是创建自己的类型 UserId(class 或结构)并在两个地方使用它。因此,如果您的程序中的用户标识符 的结构发生变化,您可以在一个地方更改它,它适用于您的整个程序。

目前,这是不可能的,但作为一种解决方法,您可以使用 using alias directive,前提是两个接口都在同一个文件中。

在两个接口所在的文件中,添加一个 using alias 指令,如下所示:

using UserIdType = System.String;

现在,您可以在 UserIUserService 中使用 UserIdType 而不是 String。当你想改变 Id 属性 的类型时,只需改变 using alias 指令,而不必改变 Id 或参数 [=17] 的类型=].


但是,您是否仍然需要更改依赖于 Id 属性 的代码?与您必须进行的所有其他代码更改相比,更改一件额外的东西并没有那么麻烦。