如何用where指定泛型?

Sam*_*tar 7 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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Error   3   ; expected
Run Code Online (Sandbox Code Playgroud)

加上其他错误:

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
Run Code Online (Sandbox Code Playgroud)

我的通用编码有明显错误吗?

更新:

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

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

从派生类调用它:

    public void AddOrUpdate(Account account)
    {
        base.AddOrUpdate<Account, IAzureTable<Account>>(account, _accountRepository);
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 12

您需要第二个whereV:

public void AddOrUpdate<T, V>(T item, V repo)
    where T : IAuditableTable
    where V : IAzureTable<TableServiceEntity>
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*iec 5

有些事情似乎错了.

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

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

public void AddOrUpdate<T,V>(T item, V repo) where ....
Run Code Online (Sandbox Code Playgroud)

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

V.AddOrUpdate(item);
Run Code Online (Sandbox Code Playgroud)

应该

repo.AddOrUpdate(item);
Run Code Online (Sandbox Code Playgroud)