在接口c#中的方法内调用方法

时间:2014-07-01 07:47:32

标签: c#

如何在c#中使用接口时调用同一类中方法内的方法?尝试访问时遇到错误(object as baseclass).method

interface IAccount 
{ 
    string fullName{get;set;} 
    void Balance();
}

public class User : IAccount 
{ 
  public string fullName { get; set; } 
  public int balance = 10000; 
  public User(string firstName, string lastName) 
  { 
    fullName = firstName + lastName; 
  } 
  public void IAccount.Balance() 
  { 
    Console.WriteLine("Account balance-" + this.balance); 
  } 
  public void MyBalance() 
  { 
    Console.WriteLine(" My balance"); 
    IAccount.Balance(); 
  }
}

2 个答案:

答案 0 :(得分:2)

尝试从IAccountonpublic void Balance()内部删除public void MyBalance()

interface IAccount 
{ 
    string fullName{get;set;} 
    void Balance();
}

public class User : IAccount 
{ 
  public string fullName { get; set; } 
  public int balance = 10000; 
  public User(string firstName, string lastName) 
  { 
    fullName = firstName + lastName; 
  } 
  public void Balance() 
  { 
    Console.WriteLine("Account balance-" + this.balance); 
  } 
  public void MyBalance() 
  { 
    Console.WriteLine(" My balance"); 
    Balance(); 
  }
}

输出:

Account balance-10000
 My balance
Account balance-10000

答案 1 :(得分:0)

当您创建名为InternfaceName.MethodName的方法时,它被称为显式接口实现
这意味着该方法只能通过接口类型的引用来访问。

那么......你如何从班级内调用该方法?将this强制转换为接口类型!

public void MyBalance() 
{ 
    Console.WriteLine(" My balance"); 
    ((IAccount)this).Balance(); 
}