如何用where指定泛型?

时间:2011-12-19 09:26:24

标签: c#

我尝试指定此通用但我收到多个错误:

    public void AddOrUpdate(T item, V repo) where T: IAuditableTable, V: IAzureTable<TableServiceEntity>
    {
        try
        {
            V.AddOrUpdate(item);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding account");
            throw _ex;
        }
    }

例如,在第一行的V之后的“:”给出错误:

Error   3   ; expected

加上其他错误:

Error   2   Constraints are not allowed on non-generic declarations 
Error   6   Invalid token ')' in class, struct, or interface member declaration 
Error   5   Invalid token '(' in class, struct, or interface member declaration 
Error   7   A namespace cannot directly contain members such as fields or methods   
Error   8   Type or namespace definition, or end-of-file expected

我的通用编码是否存在明显错误?

更新

我做了更改,代码现在看起来像这样:

public void AddOrUpdate<T, V>(T item, V repo)
        where T : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
        where V : IAzureTable<TableServiceEntity>
    {
        try
        {
            repo.AddOrUpdate(item);
        }
        catch (Exception ex)
        {
            _ex.Errors.Add("", "Error when adding account");
            throw _ex;
        }
    }

从派生类调用它:

    public void AddOrUpdate(Account account)
    {
        base.AddOrUpdate<Account, IAzureTable<Account>>(account, _accountRepository);
    }

2 个答案:

答案 0 :(得分:12)

where需要第二个V

public void AddOrUpdate<T, V>(T item, V repo)
    where T : IAuditableTable
    where V : IAzureTable<TableServiceEntity>

每个where列出单个类型参数的约束。请注意,我已经将类型参数添加到方法中 - 否则编译器将寻找TV作为普通类型,并且不理解为什么要尝试约束它们。

答案 1 :(得分:5)

有些事情似乎错了。

1)正如@Jon所说,你需要单独的where条款

2)您需要在方法上定义泛型:

public void AddOrUpdate<T,V>(T item, V repo) where ....

3)您正尝试在类型V上调用方法,而不是此类型repo的实例。即,这个:

V.AddOrUpdate(item);

应该是

repo.AddOrUpdate(item);