請清除約run time polymorphism
請清除 - 要在c#中實現運行時多態性,我們使用Interface?
這是真的嗎?
爲了實現c#中的運行時多態性,我們使用Interface?
我已經瀏覽了SO上的所有帖子。答案並不是直截了當的矛盾。我希望答案是/否請幫助我
請清除約run time polymorphism
請清除 - 要在c#中實現運行時多態性,我們使用Interface?
這是真的嗎?
爲了實現c#中的運行時多態性,我們使用Interface?
我已經瀏覽了SO上的所有帖子。答案並不是直截了當的矛盾。我希望答案是/否請幫助我
您不必爲此定義單獨的接口。您也可以使用基類來實現多態。
欲瞭解更多信息查看本頁面:
在C#中使用多態的例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Animals
{
class Program
{
static void Main(string[] args)
{
List<Animal> animals = new List<Animal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach(Animal animal in animals)
{
animal.PrintWhoAreYou();
}
Console.ReadKey();
}
}
abstract class Animal
{
public abstract void PrintWhoAreYou();
private bool feeded = false;
public void Feed()
{
feeded = true;
}
}
class Dog : Animal
{
public override void PrintWhoAreYou()
{
Console.WriteLine("I am a dog!");
}
}
class Cat : Animal
{
public override void PrintWhoAreYou()
{
Console.WriteLine("I am a cat!");
}
}
}
正如你可以看到使用一個基類,你可以在基本定義常用功能類,而不是重複代碼。
您可以使用一個接口來定義由實現此接口的類提供的一組公共方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Animals
{
class Program
{
static void Main(string[] args)
{
List<IAnimal> animals = new List<IAnimal>();
animals.Add(new Dog());
animals.Add(new Cat());
foreach(Animal animal in animals)
{
animal.PrintWhoAreYou();
}
Console.ReadKey();
}
}
interface IAnimal
{
void PrintWhoAreYou();
}
abstract class Animal : IAnimal
{
public abstract void PrintWhoAreYou();
private bool feeded = false;
public void Feed()
{
feeded = true;
}
}
class Dog : Animal
{
public override void PrintWhoAreYou()
{
Console.WriteLine("I am a dog!");
}
}
class Cat : Animal
{
public override void PrintWhoAreYou()
{
Console.WriteLine("I am a cat!");
}
}
}
嗯,這不是一個虛假的說法。您可以使用接口實現動態/運行時多態(後期綁定),但您也可以在運行時確定基礎具體類型的基類或抽象類。後期綁定的一個例子。 ..
應該有以下接口
interface IOrder
{
void ProcessOrder(int orderId);
void ProcessOrder(int orderId, int userId);
}
然後,你必須實現該接口的命令對象......
public StoreAOrder : IOrder {...}
然後使用依賴注入來處理訂單。 ...
public class OrderProcessor
{
private IOrder order;
public OrderProcessor(IOrder _order)
{
order = _order;
}
public void Process()
{
order.ProcessOrder(id, User.Current.Id);
}
}
請注意,在編譯timw時OrderProcessor
d我們不知道實現IOrder
的具體類是什麼。此外,它不知道底層對象公開的重載。這就是所謂的運行時多態性。
回答[這裏](http://stackoverflow.com/questions/8701345/learning-to-use-interfaces-effectively)? – PakkuDon
是的,我已經通過了所有的帖子。答案並不是直截了當的矛盾。 我希望在是/否 答案請幫助我。 – Neo
@ user1723204是的,有編譯時多態性和運行時多態性 – Leo