gpt4 book ai didi

c# - 如何在没有显式转换的情况下始终获得正确的类型

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

<分区>

这是我的问题。我有以下 2 个类:

public class C1
{
public C1 GetThis()
{
return this;
}
}

public class C2:C1
{

}

现在,我想按以下方式使用这些类:

private static void Main(string[] args)
{
C1 c1 = new C1().GetThis(); //1st line
C2 c2 = new C2().GetThis(); //2nd line
}

然而,第二行不起作用。为了让它工作,我必须像这样投:

C2 c2 = (C2)new C2().GetThis(); //2nd line

但是,我是一个非常懒惰的人,尽量避免编写显式转换(强制转换)。所以问题是:我应该如何更改 GetThis() 方法的实现/声明,以便第二行无需任何转换即可工作?

感谢您的任何提示。

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