将通用T限制为特定类型 [英] Restrict generic T to specific types

查看:63
本文介绍了将通用T限制为特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

public static IResult<T, String> Validate<T>(this T value) {
} // Validate

如何将T限制为Int16,Int32,Int64,Double和String?

How can I restrict T to be Int16, Int32, Int64, Double and String?

推荐答案

您不能以这种方式限制泛型,只能选择单个类作为约束.您必须进行5次重载,或者找到所有5种东西共享并使用的接口.您选择哪个选项将取决于 Validate doe.

You can't restrict generics in that way, you can only choose a single class as a constraint. You must either make 5 overloads or find a interface all 5 of those things share and use that. Which option you choose will depend on what Validate doe.

这是您如何处理重载.

public static IResult<Int16, String> Validate<T>(this Int16 value) {
} // Validate

public static IResult<Int32, String> Validate<T>(this Int32 value) {
} // Validate

public static IResult<Int54, String> Validate<T>(this Int64 value) {
} // Validate

public static IResult<double, String> Validate<T>(this double value) {
} // Validate

public static IResult<String, String> Validate<T>(this String value) {
} // Validate

这里是通过使用公用界面,列出的所有成员实施

Here is by using a common interface, all of the members you list Implement IConvertible so you could restrict by that, however this will allow any IConvertible not just the 5 you listed.

public static IResult<T, String> Validate<T>(this T value) where IConvertible {
} // Validate

这篇关于将通用T限制为特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆