[英]Using an Interface as a Parameter Type For Method, Can this work?
我的問題是,如果您有以下形式的方法:
public bool ProcessAggregation(IAggregatePoint point) { #do stuff }
還有一個 class,NetworkAggregation,實現 IAggregatePoint。 你可以調用這樣的方法: ProcessAggregation(point) 這里的點是一個 NetworkAggregation 實例嗎?
此外,如果不能使用接口,抽象基礎 class 的 inheritance 可以工作嗎? 意味着從抽象基礎 class 繼承的任何 object 都可以傳遞到該方法中嗎?
我不願意使用 inheritance 更改類,因為它們是 MySql 數據庫/與 EntityFramework 一起使用的數據庫模式。
謝謝!
網絡聚合的實現方式如下:
public class NetworkAggregation : IAggregatePoint
{
public DateTime? AssessmentDate {get; set;}
public int Id {get; set;}
public string DUPValue {get; set;}
//And so on, other properties not specified in IAggregatePoint
}
IAggregatePoint 的實現方式如下:
public interface IAggregatePoint
{
public DateTime? AssessmentDate {get; set;}
}
是的,這會起作用。 只要 class 實現IAggregatePoint
接口,就可以將 class 的實例提供給ProcessAggregation
,而不會出現任何問題。 如果您犯了錯誤(例如嘗試使用來自NetworkAggregation
但不是ProcessAggregation
中IAggregatePoint
的一部分的方法),您將收到編譯器錯誤。
正如您所提到的,您也可以使用抽象基礎 class 做同樣的事情。
查看C# 語言規范關於接口的文檔可能是值得的。
編輯 - 這是一個簡單的工作示例:
public interface IAggregatePoint
{
}
public class NetworkAggregation : IAggregatePoint
{
}
public class AnotherAggregation
{
}
public void Test()
{
// works because NetworkAggregation implements IAggregatePoint
ProcessAggregation(new NetworkAggregation());
// fails to compile (as expected) because AnotherAggregation
// doesn't implement IAggregatePoint
ProcessAggregation(new AnotherAggregation());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.