sách gpt4 ai đã đi

c# - 排除通用约束中的类型(可能?)

In lại 作者:行者123 更新时间:2023-11-30 18:27:21 31 4
mua khóa gpt4 Nike

是否可以从可能的类型集中排除特定类型,这些类型可以在泛型参数中使用?如果是这样的话。

Ví dụ

Foo() : where T != bool

表示除 bool 类型之外的任何类型。

biên tập

Tại sao?

以下代码是我尝试强制执行负约束。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
void tĩnh Main(string[] args)
{
var x1=Lifted.Lift("A");
var x2=Lifted.Lift(true);
}
static class Lifted
{
// This one is to "exclude" the inferred type variant of the parameter
[Obsolete("The type bool can not be Lifted", true)]
static public object Lift(bool value) { throw new NotSupportedException(); }
// This one is to "exclude" the variant where the Generic type is specified.
[Obsolete("The type bool can not be Lifted", true)]
static public Lifted Lift(bool value) { throw new NotSupportedException(); }
static public Lifted Lift(T value) { return new Lifted(value); }
}

public class Lifted
{
internal readonly T _Value;
public T Value { get { return this._Value; } }
public Lifted(T Value) { _Value = Value; }
}
}
}

如您所见,它涉及到对重载决议正确性的一些信念,以及一些@jonskeet 式的邪恶代码。

注释掉处理推断类型示例的部分,它不起作用。

如果有排除的通用约束会好得多。

1 Câu trả lời

不,您不能像使用类型约束那样进行一次性排除。不过,您可以在运行时执行此操作:

public void Foo()
{
if (typeof(T) == typeof(bool))
{
//throw exception or handle appropriately.
}
}

关于c# - 排除通用约束中的类型(可能?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26888003/

31 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com