5

ジェネリック型を作成するにはどうすればよいですか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 の型のみを受け入れるジェネリックを作成することは可能ですか?

4

2 に答える 2

10

クラス宣言に制約がない可能性がありますが、静的コンストラクターで型チェックを行います。

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>

編集:

上でマシュー・ワトソンが指摘しているように、本当の答えは「できないし、すべきではない」です。面接担当者がそれが間違っていると信じている場合は、とにかくそこで働きたくないでしょう ;)

于 2013-05-14T11:32:48.800 に答える
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();
    }
}
于 2013-05-14T11:47:59.937 に答える