gpt4 book ai didi

c# - 为什么我的泛型约束仍然需要转换?

转载 作者:行者123 更新时间:2023-11-30 12:30:40 25 4
gpt4 key购买 nike

谁能阐明为什么调用下面的“DoTest1”方法会出现问题?

至于为什么我需要将传入的 GridCore 对象仍然转换为通用类型 T,即使我指定 T 派生自 GridCore 并使用我的 where T : GridCore?

谢谢

public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
MyTest<MyAlbum> mytest = new MyTest<MyAlbum>();
mytest.DoTest1(new MyAlbum());
mytest.DoTest2(new MyAlbum());
}
}

public class GridCore { }

public class MyAlbum : GridCore
{
public string Title { get; set; }
}

public class MyTest<T> where T : GridCore
{
private List<T> _list = new List<T>();

public void DoTest1(GridCore ma)
{
//_list.Add(ma); <-- why doesn't this work?
_list.Add((T)ma);
}

public void DoTest2(T ma)
{
_list.Add(ma);
}

}

最佳答案

如果您希望您的方法推断出 GridCoreT(因为约束),那么在编译时它不能.这就是您收到错误的原因。

Generic Methods (C# Programming Guide)

The compiler can infer the type parameters based on the method arguments you pass in; it cannot infer the type parameters only from a constraint or return value.

关于c# - 为什么我的泛型约束仍然需要转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15677638/

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