【问题标题】:Generic class accepts primitive type and string泛型类接受原始类型和字符串
【发布时间】:2013-05-14 11:27:55
【问题描述】:

如何创建accepts only a type of Integer, Long and String. 的泛型类型

我知道我们可以限制单个类的类型或通过使用以下代码实现接口

public class MyGenericClass<T> where T:Integer{ }

或处理 int,long 但不处理字符串

public class MyGenericClass<T> where T:struct 

是否可以创建一个只接受 Integer、Long 和 String 类型的泛型?

【问题讨论】:

  • 你确定泛型是你想要的吗?泛型通常用于全面使用。你到底想解决什么问题?
  • @Moo-Juice 这是面试官问的。我问需要,他回复that is requirement :(
  • 我的回答是“你不能,如果可以的话,它也不会是适当的泛型。改为编写三个单独的类。”

标签: c# generics collections


【解决方案1】:

您可能在类声明中没有约束,但在静态构造函数中进行一些类型检查:

public class MyGenericClass<T>
{
    static MyGenericClass() // called once for each type of T
    {
        if(typeof(T) != typeof(string) &&
           typeof(T) != typeof(int) &&
           typeof(T) != typeof(long))
            throw new Exception("Invalid Type Specified");
    } // eo ctor
} // eo class MyGenericClass<T>

编辑:

正如 Matthew Watson 上面指出的那样,真正的答案是“你不能也不应该”。如果你的面试官认为是不正确的,那么你可能不想在那里工作;)

【讨论】:

  • 是否可以进行编译时检查?这限制在运行时
  • @Billa,不,但您可以添加一些额外的接口来减少可能的情况,例如IComparable, IConvertible
  • @ChrisSinclair,“never” 有点太强了——拥有完全信任权限,你可以做各种讨厌的事情,including creating instances where no constructor was run
  • @Lucero 哈哈,很公平。您仍然可以像上面那样应用运行时检查,但这会在编译时提供一些保证,除了tomfoolery之外一切正常。
  • @JonnyPiazzi 这是一个面试问题......谁知道为什么?
【解决方案2】:

我建议您使用构造函数来显示可接受的值,然后将值存储在对象中。像下面这样:

class MyClass
{
    Object value;

    public MyClass(int value)
    {
        this.value = value;
    }

    public MyClass(long value)
    {
        this.value = value;
    }

    public MyClass(string value)
    {
        this.value = value;
    }

    public override string ToString()
    {
        return value.ToString();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-03
    • 2015-08-27
    • 2010-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多