我的同事和我在研究獲取委託的調用列表時發現了這個問題。如果你在類X中創建一個事件,那麼你可以在該類中訪問該事件的公共方法。但是(並且請忽略諸如爲什麼你有公共訪問類成員的東西,這不是我們要求的東西!),如果我們有一個類Y實例化X,並訪問X中的事件,它不能調用任何公共方法,例如事件的GetInvocationList()。我們想知道這是如何工作的。下面是一個代碼示例(閱讀評論,看看我們的意思):如何使公共方法僅在類本身和擁有C#中的對象的類中可見?
public class X
{
public delegate void TestMethod();
public event TestMethod testMethod;
private void rubbish()
{
// can access testMethod.GetInvocationList() fine here
testMethod.GetInvocationList();
}
}
public class Y
{
public Y()
{
X x = new X();
x.testMethod += this.test;
// here it says testMethod can only appear on the left hand side of += or -=
// why is this? (i.e. the below line is invalid)
x.testMethod.GetInvocationList();
}
public void test()
{
}
}
出於好奇,你是怎麼做到這一點,並找到適合具有這種特徵avaialble的原因是什麼?
非常感謝 阿米特
你問「我怎麼能爲我自己的班級完成同樣的事情」,或者「爲什麼這樣設計事件」? – ken2k 2012-01-04 12:41:42
@ ken2k:我想都是。 – Maheep 2012-01-04 12:42:31
刪除**事件**關鍵字。 – adatapost 2012-01-04 12:42:52