将值类型转换为泛型 [英] Cast value type to generic

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

问题描述

我有一个通用类,我只需要限制为值类型(int,float等).我有一个根据类型的测试调用Parse方法的方法.例如:

I have a generic class that I need to constrain to only value types (int, float, etc.). I have a method that calls the Parse method based on a test of the type. For example:

class MyClass<T>
{
    ...

    private static T ParseEntry(string entry)
    {
        if(typeof(T) == typeof(float))
        {
            return (T) float.Parse(entry);
        }

        if(typeof(T) == typeof(int))
        {
            .... you get the idea
        }
    }
}

将T约束为struct不起作用,我真的想尽可能避免装箱/拆箱.有什么想法吗?

Constraining T to struct doesn't work and I really want to avoid boxing/unboxing if possible. Any ideas?

对此有更多的了解.我在开发的库中注意到,两个类具有非常相似的属性/方法等.唯一的区别是数据的基本类型(int或float).这使我进入了使用泛型的设计.唯一的麻烦是因为调用特定的Parse方法,具体取决于它是float还是int.我可以通过装箱/拆箱解决它,但我真的想尽可能避免这种情况.

To give a little more insight into this. I noticed in a library I'm developing that two classes had very similar properties/methods etc. the only difference was the underlying type of data (int or float). THis lead me to a design with generics. The only hangup is because of the call to the specific Parse method depending on if it's a float or int. I could get around it with boxing/unboxing but I really wanted to avoid that if possible.

推荐答案

不幸的是,您无法创建describe类型的约束.您不能写,例如:

Unfortunately, you cannot create constraints of the type of describe. You cannot write, for example:

class MyClass<T> where T : int { ... } // won't compile

将约束保留为struct可能更好,但是添加一些运行时检查以确保在实例化该类时T仅是受支持的类型之一.既然您还没说太多计划如何使用班级的方法,那么就如何实现更好的字体安全性很难提供替代性设计建议.

You may be better off leaving the constraint to be struct, but add some runtime checks to make sure that T is only one of the supported types when you instantiate the class. Since you haven't said much how you're planning to use your class - it's hard to offer alternative design advice on how to achieve better type safety.

您应该查看Marc和其他人推荐的类型转换器选项.这似乎是要走的路.

You should look at the type converter option that Marc and others recommend. This seems like the way to go.

对我来说,一个可能的想法是使Parse()方法实际上是一个委托:Func<string,T>-您在构造期间分配的.这将使您能够:

One possible idea that occurs to me, is to make the Parse() method actually be a delegate: Func<string,T> - that you assign during construction. This would make it possible for you to:

  1. 避免无效/笨拙的if/else逻辑.
  2. 将类的未来使用改进为其他值类型(结构,BigDecimal等)

这是我的意思的代码示例:

Here's a code example of what I mean:

class MyClass<T>
{
    private readonly Func<string,T> ParseEntry;

    public MyClass( Func<string,T> parser )    
    {
        ParseEntry = parser;
    }
}

public static class AvailableParsers
{
    public static Func<string,int> ParseInt = s => int.Parse( s );
    public static Func<string,float> ParseFloat = s => float.Parse(s);
}

您可以在此处了解有关可用约束的信息.可用的唯一约束是:

You can read about the available constraints here. The only constraints available are:

  • 结构(可选)
  • new()(可选)
  • 界面约束(可选,多个允许)
  • 基类约束(可选,仅允许一个约束)
  • 裸约束(例如T:TResult)

这篇关于将值类型转换为泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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