gpt4 book ai didi

c# - 在 DLL 中使用 default 关键字

转载 作者:可可西里 更新时间:2023-11-01 03:02:11 26 4
gpt4 key购买 nike

我在使用 default 时遇到了一个非常奇怪的问题DLL 项目中的关键字。在我的 DLL 项目(用 VS2013 编译)中,我有以下类:

public class BaseClass<T>
{
public T value;
public bool enabled;

public BaseClass ( T value = default(T), bool enabled = true )
{
this.value = value;
this.enabled = enabled;
}
}

现在,如果我在 DLL 项目中使用它,它会完美运行。我可以毫无问题地创建派生自该基类的类。但是,一旦我尝试在另一个项目(使用 Mono 2.0.0 编译)中使用 DLL,从具有值类型的基类派生会导致编译器错误。这:

public class ChildClass : BaseClass<int>
{
}

原因:

Assets/ChildClass.cs(8,14): error CS1502: The best overloaded method match for BaseClass<int>.BaseClass(int, bool)' has some invalid arguments

Assets/ChildClass.cs(8,14): error CS1503: Argument #1' cannot convertnull' expression to type `int'

但是,具有值类型的基类可以毫无问题地用于字段中:

public class OtherClass
{
public BaseClass<int> baseInt;
}

我使用 ILSpy 查看了 DLL 并注意到了这一点:

public class BaseClass<T>
{
public T value;
public bool enabled;
public BaseClass(T value = null, bool enabled = true)
{
this.value = value;
this.enabled = enabled;
}
}

请注意 default<T>在构造函数中已替换为 null .这似乎是问题的原因,因为 null 将是值类型的无效值。

那么这里发生了什么?

编辑:正如在评论中发现的那样,当第二个项目使用 VS2013 或更新版本的 Mono 编译时,不会发生这种情况。

最佳答案

这似乎是单声道编译器 3.2.3 之前的错误(@usr 在他们最初的评论中是非常正确的)。编译器将默认参数值作为属性插入到程序集元数据中(参见 this answer )。我验证了 ilspy 的输出与将 default(T) 编码为 .param [1] = nullref 的 ildasm 一致。我怀疑约定是将通用 default(T) 编码为 null 并且消费编译器应该知道如何使用它。似乎与this issue有关,但是,根据日期,此特定问题在报告之前的某个时间已得到修复。

关于c# - 在 DLL 中使用 default 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26763434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com