[英]Is it possible to access the other members of an interface type?
我很好奇這是否可能,如果沒有,那么它背后的原因是什么,以及如何處理這種編程方案?
假設我有這個界面:
public interface IBook
{
void BookClient();
void CancelClient();
}
我有這個實現上述接口的類:
public class Photographer : IBook
{
public void BookClient()
{
// do something
}
public void CancelClient()
{
// do something
}
// non-interface methods
public void SaveClients()
{
// do something
}
public void DeleteClients()
{
// do something
}
}
現在,如果我將此類分配給我的代碼中的某個接口類型,例如:
IBook photo;
photo = new Photographer();
是否有可能做到這一點:
// non-interface member from the Photographer class
photo.SaveClients();
有人可以在這個問題上理順我,也許可以指出我正確的方向。 謝謝。
是的,這是可能的,但您必須先將photo
投入Photographer
:
// non-interface member from the Photographer class
((Photographer)photo).SaveClients();
僅使用photo.SaveClients()
語法是photo.SaveClients()
,因為您可以輕松地創建另一個類:
class TestClass : IBook
{
public void BookClient()
{
// do something
}
public void CancelClient()
{
// do something
}
}
並使用它:
IBook photo;
photo = new Photographer();
photo = new TestClass();
// what should happen here?
photo.SaveClients();
因此,只要將變量用作接口實現,就只能訪問該接口中聲明的成員。 但是,該對象仍然是一個類實例,因此您可以使用其他類成員,但必須首先顯式轉換為該類型。
接口類型只能引用接口成員。 您正在嘗試調用不屬於該接口的類的成員。
你可以試試(現在不能測試):
IBook photo;
photo = new Photographer();
(photo as Photographer).SaveClients();
// or
((Photographer)photo).SaveClients();
是的,有可能,使用反射。 您也可以投射到Photographer
,然后調用SaveClients()
。
在我看來,一個好的解決方案是定義您需要在界面中調用的每組操作,然后,轉換為該界面,並調用您需要的方法:
public interface IBook
{
void BookClient();
void CancelClient();
}
public interface IClient
{
void SaveClients();
}
然后用作:
IBook photo = new Photographer();
// now cast photo object as a IClient
IClient client = photo as IClient;
if (client != null)
{
client.SaveClients();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.