sách gpt4 ai đã đi

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

In lại 作者:行者123 更新时间:2023-12-04 02:19:27 26 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 -esque 邪恶的代码。

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

排除通用约束会好得多。

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/10642751/

26 4 0
Bài viết được đề xuất: BlackBerry touchEvent 外场触发 fieldChanged
Bài viết được đề xuất: json - 容错 JSON 解析
Bài viết được đề xuất: javascript - 在javascript中分组和求和哈希数组
Bài viết được đề xuất: asp.net - 请帮我理解 web.config 自定义设置的类型属性?
行者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