接口无法封装方法 [英] Interface unable to encapsulate method

查看:67
本文介绍了接口无法封装方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As I learn that interface is also used for encapsulate method but in the following code by casting ojb to MainClass I am able to access other method from Mainclass which I did not declare in interface so now where is encapsulation occur.

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";
    }
}

推荐答案

我刚回答了一个非常类似的问题 - 这也是你的问题。



不要重新发布 - 浪费时间,让人烦恼。



但是 - 有一个区别在于,您将变量 obj 声明为 IInterface 类型,这意味着它可以包含一个实例具有implements IInterface 的任何类,并将变量转换为特定的派生类类型 - 这意味着(如果转换成功)它将是 MainClass 实例然后您可以使用所有 MainClass 字段,属性和方法。



如果它不是 MainClass 实例,而是实现 IInstance 的另一个类,那么你将得到一个运行时来自演员的错误 - 但是在你的应用程序运行之前系统肯定不知道。
I just answered a very similar question to this - and that was yours as well.

Don't repost - it wastes time and annoys people.

But - there is a difference here, in that you are declaring your variable obj as a IInterface Type, which means it can contains an instance of any class with implements IInterface, and casting the variable to a specific derived class type - which means that (if the cast is successful) it will be a MainClass instance and you can then use all MainClass fields, properties, and methods.

If it isn't a MainClass instance, but a different class that implements IInstance then you will get a runtime error from the cast - but the system cannot definitely know that until your application runs.


这篇关于接口无法封装方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆