2014-07-01 27 views
-7

如何在c#中使用接口時調用同一類中的方法內的方法?我有錯誤時通過(對象作爲基類)試圖訪問。方法在接口c中的方法內的調用方法#

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(); 
    } 
} 
+5

我們可以看到一些代碼嗎? – Neel

+0

和您嘗試調用方法內的方法的代碼? – Carsten

+1

錯誤是什麼?請在將來使用**編輯**按鈕更新您的問題。 – Sayse

回答

0

當你創建一個名爲InternfaceName.MethodName的方法,它被稱爲顯式接口實現
這意味着該方法只能通過接口類型的引用訪問。

所以...你怎麼能從課堂上調用這種方法?將接口類型轉換爲this

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

謝謝..這是我需要的答案 – user3792939

+0

然後標記爲:P –

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

歡迎您:) – Carsten

+0

嗨,你好嗎:)))) –

+0

我認爲你得到的提示 - 如果不看看你使用的編輯和我給的評論: P – Carsten