限制T可串和诠释? [英] Restricting T to string and int?

查看:107
本文介绍了限制T可串和诠释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了自己是这样定义泛型集合类。

 公共类StatisticItemHits< T> {...} 

这类可以用 INT 和字符串值只要。然而,这



 公共类StatisticItemHits< T>其中T:字符串,整数{...} 



将无法编译。我在做什么错了?


解决方案

类型限制是为了与接口一起使用

。您的样本表明,要允许类从int和字符串,这是有点扯淡继承。我建议你设计一个包含您将要使用在你的泛型类StatisticItemHits方法的接口,并使用该接口的限制。不过,我实在不明白你的要求在这里,也许你可以张贴关于您的方案一些细节?


I have built myself a generic collection class which is defined like this.

public class StatisticItemHits<T>{...}

This class can be used with int and string values only. However this

public class StatisticItemHits<T> where T : string, int {...}

won't compile. What am I doing wrong?

解决方案

The type restriction is meant to be used with Interfaces. Your sample suggests that you want to allow classes that inherit from int and string, which is kinda nonsense. I suggest you design an interface that contains the methods you'll be using in your generic class StatisticItemHits, and use that interface as restriction. However I don't really see your requirements here, maybe you could post some more details about your scenario?

这篇关于限制T可串和诠释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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