gpt4 book ai didi

c# - 使用泛型进行显式转换

转载 作者:太空宇宙 更新时间:2023-11-03 20:52:51 24 4
gpt4 key购买 nike

<分区>

我有一个代码片段:

public interface IMyInternalClass
{
}

public class MyInternalClass : IMyInternalClass
{
}

public interface IMyClass
{
T GetInternalObject<T>();
}

public class MyClass: IMyClass
{
private readonly MyInternalClass _internalObject;

public T GetInternalObject<T>()
{
return (T)(IMyInternalClass)_internalObject;
}

public MyClass(MyInternalClass internalObject)
{
_internalObject = internalObject;
}
}

GetInternalObject<T>用法:

IMyInternalClass internalObject = myClass?.GetInternalObject<IMyInternalClass>();

如果我尝试通过 return (T)_internalObject; 使用显式转换- 它不会工作并且会失败并出现错误“无法将类型‘MyInternalClass’转换为‘T’

那么,在不触及此代码示例的设计的情况下,我为什么要将其显式转换为 (IMyInternalClass)?第一?

There is another question Cannot convert type: why is it necesssary to cast twice? but there is no information regarding interface usage as in this case.

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