c# - 如果我指定了基类,为什么我不能用泛型调用参数化构造函数

标签 c# .net generics constructor compiler-errors

如果有下面的类:

class A
{
    public A(int number)
    {
    }
}

那么为什么我不能有这样一个泛型类:

class B<ParameterClass> where ParameterClass : A
{
    public B()
    {
        ParameterClass a = new ParameterClass(1);
    }
}

我得到一个 CS0304,编译器说我没有 new() 限制,但我只想调用在 A 上定义的构造函数,因为 ParameterClass 始终是 A,编译器可以确保 A( int number) 构造函数将始终存在。我只是不明白为什么会有这个限制。

最佳答案

仅仅因为构造函数是在 A 上声明的,并不意味着它将在 ParameterClass 上声明。例如:

public class Bad : A
{
    public Bad(string x) : base(x.Length)
    {
    }
}

现在我使用:

var b = new B<Bad>();

您希望它做什么?按照您编写它的方式,如果它有效,我希望它会尝试调用 new Bad(1),这肯定是无效的。

关于c# - 如果我指定了基类,为什么我不能用泛型调用参数化构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14838964/

相关文章:

asp.net - 将 System.Web.HttpContext.Current 转换为 System.Web.HttpContextBase

c# - 无法为类型 'IconService' 上的属性 'Microsoft.Fast.Components.FluentUI.FluentIcon' 提供值

c# - 在 Windows Phone 7 中通过 http 流式传输使用 .pls 文件播放广播

c# - 系统.日期时间.ParseExact : unrecognized format string

c# - 仅使用 DropDown 进行 DateTimePicker 选择

c# - 如何将事件传递给方法然后订阅它?

.NET 4.0 Cast 通用接口(interface)

c# - 在 C# 中调用泛型 T 作为属性。我 :e [typeof(List<T>)]

generics - 使用 mem::size_of::<T> 作为数组长度时,编译时无法知道类型 `T` 的值的大小

c# - 我无法修复代码分析规则 CA2202