我喜歡做這樣的事情,但不知道如何解決它。假設我針對和介面撰寫了不同的類:
public class A : IMyInterface
{
public string name = "NameOfA";
public string description = "descriptiontextA";
}
public class B : IMyInterface
{
public string name = "NameOfB";
public string description = "descriptiontextB";
}
public class programm
{
void DoSmthSpecial(var class)
{
Console.WriteLine($"This is {class.name}");
}
}
其中var類應該是A類或B類。所以基本上我為不同的類呼叫了類似的方法。有人可以幫忙嗎?
uj5u.com熱心網友回復:
你的界面應該定義任何公共屬性:
public interface IMyInterface
{
string Name {get;}
string Description {get;}
}
然后由您的類實作:
public class A : IMyInterface
{
public string Name {get;} = "NameOfA";
public string Description {get;} = "descriptiontextA";
}
public class B : IMyInterface
{
public string Name {get;} = "NameOfB";
public string Description {get;} = "descriptiontextB";
}
現在您的DoSmthSpecial方法可以使用此介面:
void DoSmthSpecial(IMyInterface myClass)
{
Console.WriteLine($"This is {myClass.Name}");
}
你可以這樣稱呼它:
IMyInterface myInst = new A();
DoSmthSpecial(myInst);
或者像這樣:
A myInst = new A();
DoSmthSpecial(myInst);
在線嘗試
uj5u.com熱心網友回復:
介面的想法是將某些實作類的形狀宣告為想要與具有特定形狀/能夠以某種一般方式表現的物件互動的代碼,但不關心實作類的實際作用。這可以采取屬性和方法的形式
public interface IMyInterface{
string Name {get;set;}
string GetSomethingCool();
}
public class A : IMyInterface
{
public string Name {get;set;} = "NameOfA";
public string GetSomethingCool() => "SomethingCool";
}
public class B : IMyInterface
{
public string Name {get;set;} ;
public string GetSomethingCool() => "S" "OMETHING".ToLower() string.Concat(new[] {'C', 'o', 'o', 'l' });
public B(){
Name = Guid.NewGuid().ToString();
}
}
public class Program
{
static void DoSmthSpecial(IMyInterface x)
{
//here you can use anything that is available on IMyInterface, property or method
Console.WriteLine(x.GetSomethingCool());
Console.WriteLine(x.Name);
//avoid the temptation to inspect the type of x and do subclass specific stuff
if(x is A a)
a.SomethingOnlyOnA(); //avoid
}
static void Main(){
//can pass an A or a B in as something that validly implements IMyInterface
DoSmthSpecial(new A());
DoSmthSpecial(new B());
}
}
這兩個類從方法回傳相同字串的GetSomethingCool()方法非常不同,設定 Name 屬性的策略也不同——呼叫代碼不知道也不關心值是如何生成的;它只是從介面中知道有一個方法/屬性具有某個名稱,它可以呼叫并獲取/設定資料/執行該方法的操作。
uj5u.com熱心網友回復:
像這樣使用泛型
void DoSmthSpecial<T>(T class)
{
// your code here
}
并像這樣呼叫這個方法。
B objB = new B();
DoSmthSpecial<B>(objB);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/429769.html
