本文介绍了接口变量无法访问所有类方法的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个界面和一个类见下:

  interface  ILastName 
{
string LastName();
}

class MyName:ILastName
{
public string FirstName()
{
return Michael;
}

public string LastName()
{
return Dutt;
}
}





现在看看我的以下问题和假设

1)

 MyName myNameObj =  new  MyName(); 





在上面的代码行中新的Myname()有助于创建类的Object并在堆中分配内存这意味着MyName的所有方法都存在于堆中以供访问。和myNameObj包含对该内存的引用,这意味着我们可以使用myNameObj访问所有方法。 (方法名称)。



但是

2)

 ILastName obj =  new  MyName(); 





在上面的行中,同样的事情发生在新的Myname()创建类n的对象在堆中占用内存意味着所有可以在堆中访问的方法。



但我们只能访问接口中存在的那些方法,请参阅以下行我可以访问

 obj.LastName(); 





但是以下是不可能的?为什么?

 obj.FirstName(); 





为什么? obj还持有对MyName类在myNameObj中的MyName类占用的内存的引用,那么我们无法访问接口中不存在的方法???请帮我解决这个困惑。

解决方案



I have one interface and a class see below:

interface ILastName
{
   string LastName();
}

class MyName : ILastName
{
   public string FirstName()
   {
      return "Michael";
   }

   public string LastName()
   {
      return "Dutt";
   }
}



Now see my following questions and assumptions
1)

MyName myNameObj=new MyName();



in the above line of code new Myname() helps to create Object of class and it allocate memory in the heap that means all the method of MyName is present in heap for access. and myNameObj contain reference to that memory so means we can access all the method by using myNameObj. (name of method).

But
2)

ILastName obj=new MyName();



In the above line same thing happen new Myname() creating object of class n taking memory in heap that means all method available to access in heap.

But we are able to access only those methods which are present in Interface see following line I can access

obj.LastName();



but following is not possible why??

obj.FirstName();



why ?? obj is also holding the reference to the memory which is taken by MyName class in heap same as myNameObj, then we are not able to access method which is not present in interface??? please help me out for my this confusion.

解决方案




这篇关于接口变量无法访问所有类方法的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 01:26