c# - 算术类型方法的类型约束

标签 c# generics

我一直在为自己的控制台应用程序摆弄通用方法,因为有些操作对我来说似乎很常见。 我目前正在思考是否有一种方法可以通过它们包含的列表/方法将方法的输入类型限制为硬代码中的一组特定类型,这可能意味着我不必在代码中抑制警告,如果假设就在那里。这是我当前的代码:

static T GetNumber<T>() where T : new()
{
    Type type = typeof(T);
    MethodInfo TryParse = (from item in type.GetMethods() where item.Name == "TryParse" select item).ElementAt(0);

    while(true)
    {
        string input = NotNullInput();
        object[] parameters = new object[] { input, new T() };
        #pragma warning disable CS8605
        if (!(bool)TryParse.Invoke(new T(), parameters))
            Console.WriteLine($"Invalid {type.Name} input");
        else
            return (T)parameters[1];
        #pragma warning restore CS8605
    }
}

只要确保用户输入正确的格式,我知道它可能只会用于 int、float、double、long 等类型。我知道我想到使用的所有类型都包含TryParse 方法,所以如果有一种方法可以假设这一点,它就会解决所有问题。

也愿意接受有关如何改进代码的建议,因为我仍在学习如何处理类型和反射。

最佳答案

自 .NET 7 - TryParse 以来,有一个内置接口(interface)表达“此类型有一个 IParseable<T> 方法”的想法.

您可以限制T到该类型,它不仅适用于数字,还适用于任何实现 IParseable<T> 的类型。如果您只希望它适用于数字,还有子接口(interface) INumber<T>您可以使用它来代替。

示例:

public static T ParseInputAsTypeUntilSuccessful<T>() where T: IParsable<T> {
    while (true) {
        if (T.TryParse(Console.ReadLine(), CultureInfo.InvariantCulture, out var result)) {
            return result;
        } else {
            Console.WriteLine($"Invalid {typeof(T).Name} input!");
        }
    }
}

请注意,您需要指定 IFormatProvidernull ,在这里我使用了 CultureInfo.InvariantCulture .

关于c# - 算术类型方法的类型约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76430200/

相关文章:

c# - C# 中的事件注册范围

当从列表中删除引用的对象时,c# 复制的属性丢失引用

java - 通用可调用

java - 使用保存类保存值并在调用时打印先前保存的值

c# - "where T : class, new()"是什么意思?

Java:通过泛型类型的反射调用特定方法

c# - HttpClient 在 Asp.Net 中的响应返回 404(未找到 : Could not find the controller)

c# - 调用具有类名称的网站上的按钮?

Swift 3 泛型 : issue with setting UICollectionViewDatasource & Delegate for a UICollectionView inside UITableViewCell

c# - 以编程方式从基于 Claims auth 的 SharePoint 2010 站点下载文件