0

我想实现一个函数,它返回它正在操作的类型的值。请问我该怎么做?

示例 1:

static T Swap<T>(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;

    return <T> temp;
}

示例 2:

public override T GetRandom()
{
    return  (T)_random.Next(_min, _max);
}
4

2 回答 2

7

Since both the return-type and the variable-type are already T, this is just:

return temp;

Alternatively, to cast (but this is not needed here):

return (T) temp;

Actually, though, IMO a "swap" should have void return!

于 2012-05-12T07:56:47.777 回答
0

把这个通用化是没有意义的:

public override T GetRandom()
{
     return  (T)_random.Next(_min, _max);
}

随机“T”是什么意思?假设 T 是“Person”类型,返回随机 Person 是什么意思?拥有一个通用的 GetRandom 方法似乎没有任何逻辑。

如果你想要一个整数,只需指定 int 作为返回类型。

public override int GetRandom()
{
    return  _random.Next(_min, _max); 
}
于 2012-05-12T08:50:05.970 回答