这里接口的用途是什么?

本文关键字:是什么 接口 这里 | 更新日期: 2023-09-27 18:09:25

当我了解到接口也用于封装方法,但在下面的代码中,通过将ojb转换为MainClass,我能够从Mainclass访问我没有在接口中声明的其他方法,所以现在封装发生在哪里。

class Program
{
    static void Main(string[] args)
    {
        IInterface obj = new MainClass();
        Console.WriteLine(((MainClass)obj).FullName()+" " +obj.LastName());
        Console.WriteLine(((MainClass)obj).SayHello());
        Console.ReadKey();
    }
}
public interface IInterface
{
    string LastName();
}
public class MainClass:IInterface
{
    public  string FullName()
    {
        return "Raman Singh";
    }
    public string SayHello()
    {
        return "Hello Sir111";
    }
    public string LastName()
    {
        return "Chauhan";
    }
}

这里接口的用途是什么?

您混淆了interfaceencapsulation。这不是接口的作用。

An interface contains definitions for a group of related functionalities that a class or a struct can implement. By using interfaces, you can, for example, include behavior from multiple sources in a class.

Encapsulation is to hide the variables or something inside a class, preventing unauthorized parties to use. So the public methods like getter and setter access it and the other classes call these methods for accessing.

你实际上持有MainClass的实例在你的obj,一旦你cast,正如你所说的。因为你实际上是用' new MainClass();'初始化它的。这将调用MainClass的构造函数来初始化obj。这就是为什么你可以访问其他方法

您提到的第一件事是"接口也用于封装",这是错误的。接口用于抽象。

在你的代码中,你已经创建了你的类的对象,并在你调用方法时进行了类型转换。现在,如果你的方法是公共的,那么通过将它强制转换到你的类,你显然可以访问它。

只有当你的客户端不知道你的类的具体实现,并且必须通过接口访问你的方法时,你才能通过抽象隐藏其他方法。然后,在接口中声明的方法可以被客户端访问。

试着用简单的语言回答你的评论。通过语句

IInterface obj = new MainClass();

你正在创建一个MainClass类型的对象。它将创建一个新的实例,并将其引用返回到IInterface类型的变量,但在运行时。

现在,当你给接口类型分配引用时,虽然对象是MainClass,但你是使用接口变量访问它的。但是接口不知道你的类中没有继承自该接口的其他方法。所以没有必要讨论在运行时驻留在堆中的对象,因为即使编译器也不允许您访问接口变量不知道的类的其他方法。

您能够调用其他方法只是因为您再次将接口变量强制转换为您的Class类型。希望这能让事情变得容易理解。

当你将对象强制转换为MainClass时,对象引用从IInterface变为MainClass。因此,所有的MainClasses方法都是可用的,因为所述方法的可见性取决于对象引用。如果你不将你的对象强制转换为MainClass,并且让它的引用类型为IInterface,那么只有LastName方法是可见的。

你的代码是相同的编码到一个实例字段,而不是一个接口,因为强制转换(MainClass)对象正在改变它。