使用ObservableCollection <T>作为没有特定类型的参数

假设我们有两个ObservableCollection:

private ObservableCollection<Barcode> barcodeCollection; 
private ObservableCollection<User> userCollection;

我有两种方法可以用这样的数据库中的项目填充它们(我使用Backgroundworker):

 DispatcherObject.Invoke(
     new System.action(() => BarcodeCollection.Add(new Barcode(dr))));

其余方法非常重复,我想我可以将一些代码封装在一个方法中,然后像这样传递ObservableCollection:

    private void LoadCollection(ObservableCollection<T> observableCollection)
    {

    }

但是,这当然行不通。.您能给我一些提示吗?复制这两种方法的代码并只更改其中一部分,感觉很奇怪。

lw9776535 回答:使用ObservableCollection <T>作为没有特定类型的参数

如果您这样更改方法签名(向其添加通用类型参数):

@BeforeMethod
public void beforeMethod() throws Exception {
    initTest(testName here,suiteName here,description here);
}

@Test(testName = "Test Name",suiteName = "Suite Name",description = "Description")
public void Test01() throws Exception {
    //test code
}

它应该起作用,因为它将从您传递给方法的集合中推断出通用参数。但是,当然,此方法中的代码不应对类型T作任何假设(除非您使用 where 关键字指定通用类型约束)

,

根据@StasIvanov答案,您只是在签名上缺少通用类型参数:

private void LoadCollection<T>(ObservableCollection<T> observableCollection)
{
}

如果您的类具有公共接口或类,则可以将其扩展为使用特定的泛型类型,例如:

private void LoadCollection<T>(ObservableCollection<T> observableCollection) where T : IMarkDeleted
{
    //you can then use common properties within the method
    observableCollection.Where(x => !x.MarkedAsDeleted);
} 

此外,如果您计划在类中包含其他泛型方法,则可能会从中受益,在这种情况下,您只需要在类级别包含一次泛型规范即可,而您的方法则不需要它:

public class ObservableCollectionHelper<T> where T : IEntity,IMarkDeleted
{
    public static T NewItem()
    {
        return Activator.CreateInstance<T>();
    }

    private void LoadCollection(ObservableCollection<T> observableCollection)
    {
    }

    private void DeleteCollection(ObservableCollection<T> observableCollection)
    {
    }
}
本文链接:https://www.f2er.com/3013199.html

大家都在问