从抽象转换为接口时会发生什么

本文关键字:什么 接口 抽象 转换 | 更新日期: 2023-09-27 18:31:45

谁能解释一下当你从抽象/界面投射到界面时幕后到底发生了什么?
示例:假设AbstractClasse a = new Concrete()Concrete实现了IText接口和AbstractClasse,我们说IText = (IText)a

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
    class Program
    {
        interface IText
        {
            string ToText();
        }
        class Subtip : SubtitleFormat, IText
        {
            public int Error { get; set; }
            public Subtip(int error)
            {
                Error = error;
            }
            public string ToText()
            {
                return $"{Error}, Hello!";
            }
        }
        abstract class SubtitleFormat
        {
            protected int _errorCount = 1;
            public int ErrorCount
            {
                get
                {
                    return _errorCount;
                }
            }
        }
        static void Main(string[] args)
        {
            SubtitleFormat sb = new Subtip(10);
            IText sb2 = sb as IText;
            Console.WriteLine(sb.ErrorCount);
            Console.WriteLine((sb as Subtip).Error);
            Console.WriteLine(sb2.ToText());
            Console.ReadLine();
        }
    }
}

从抽象转换为接口时会发生什么

当您强制转换为接口或类时,使用相关对象的正确类型来确定它是否与目标兼容。 对象当前类型化为什么在很大程度上无关紧要 - objectinterface、最终class或基本class

因此,例如,您可以这样做:

SubtitleFormat sb = new Subtip(10);
IText sb2 = sb as IText;
Subtip sb3 = sb2 as Subtip;

这两个转换都是有效的,因此在转换结束时sb3将具有非 null 值。 所有三个变量(sbsb2sb3)都指向同一个对象,所以Object.ReferenceEquals(sb, sb3)为真。

由于对象实例的真实类型用于确定强制转换是否有效,因此如下所示的内容不起作用

public class NotIText : SubtitleFormat
{
    public string ToText()
    {
        return "";
    }
}
static void Main(string[] args)
{
    SubtitleFormat sb = new NotIText();
    IText sb2 = sb as IText;
}

类类型的值可以转换为类型对象或由类实现的接口类型,只需在编译时将引用视为另一种类型即可。同样,可以在不更改引用的情况下将 object 类型的值或接口类型的值转换回类类型(但在这种情况下当然需要进行运行时类型检查)。

来源CSharp语言规范