我有一個 A 類,B 和 C 從中繼承。我也有像這樣的 B 和 C 串列:List<B> listB和List<C> listC.
我想將元素添加到這些串列中,但前提是我做了一些邏輯。我制作了一個方法,該方法采用任何型別的串列和要添加的相關專案。
public void AddItemToList<T>(List<T> item_list, T new_item)
{
//do logic with properties of A...
}
我需要能夠將此方法與兩個串列一起使用,如下所示:
AddItemToList<B>(listB, new B());
AddItemToList<C>(listC, new C());
但是,由于型別是通用的,我無法使用 A 的屬性在方法中執行我想要的邏輯。
如果我在方法中使用型別 A,那么如果不先轉換它們,我就無法傳遞串列或專案。
有沒有辦法設定型別,以便我可以傳遞匹配的引數,同時仍然能夠在方法內執行邏輯?
uj5u.com熱心網友回復:
您可以在 T 上施加約束,where在方法宣告中使用
查看位置(泛型型別約束)
using System;
using System.Collections.Generic;
class A
{
public int PropA;
}
class B : A
{
}
class C : A
{
}
class NotDerivedFromA
{
}
class Foo
{
// where T:A force T to be A or a derived class
public void AddItemToList<T>(List<T> item_list, T new_item) where T:A
{
Console.WriteLine(new_item.PropA);
//do logic with properties of A...
}
}
public class Program
{
public static void Main()
{
List<A> listA = new();
List<B> listB = new();
List<C> listC = new();
Foo foo = new();
foo.AddItemToList<A>(listA, new A());
foo.AddItemToList<B>(listB, new B());
foo.AddItemToList<C>(listC, new C());
// this doen't compile: NotDerivedFromA doesn't satisfy the constraint
//foo.AddItemToList<NotDerivedFromA>(new List<NotDerivedFromA>(), new NotDerivedFromA());
Console.WriteLine("Hello World");
}
}
uj5u.com熱心網友回復:
如果您的泛型方法需要執行特定于型別的功能,那么它就不是泛型的。但是,您可以采用函式式方法并傳入Action<T>執行特定型別作業的委托:
public void AddItemToList<T>(List<T> item_list, T new_item, Action<T> effect)
{
effect(new_item);
// etc
}
然后呼叫它:
// `x` below is inferred to be of type `int`
AddItemToList(new List<int>(), 0 ,x => Console.WriteLine(x 1));
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/459688.html
上一篇:“瀏覽器”指的是哪個平臺?
