简体   繁体   English

可以传入通用实体并访问公共属性吗?

[英]Possible to pass in a generic entity and access a common property?

I want to have a method that checks some AccountIDs are allowed for a certain operations and in doing so, I need to get a distinct list of AccountIDs in any entity type that I pass through. 我想有一个方法来检查某些操作允许的某些AccountID,并且这样做,我需要获得我通过的任何实体类型的不同AccountID列表。

I could have a User entity, a Transaction entity, and Product entity, etc. but they will all always have an AccountID property no matter what. 我可以拥有一个User实体,一个Transaction实体和一个Product实体等,但无论如何它们都将始终具有AccountID属性。

This is some non-working code to hopefully give you the gist of what I'm trying to accomplish... 这是一些非工作代码,希望能给你我想要完成的事情的要点......

public void CheckForAccountAuthorization<T>(IQueryable<T> entityWithAccountIdProperty)
{
    IEnumerable<string> accountIdList 
        = entityWithAccountIdProperty.Select(u => u.AccountID).Distinct();

    //Do More Work...

    }
}

But it gives me the errors: 但它给了我错误:

Unknown method 'Select(?)' of 'System.Linq.IQueryable' 'System.Linq.IQueryable'的未知方法'选择(?)'

Unknown member 'AccountID' of 'T' 'T'的未知成员'AccountID'

Create some interface with AccountID property: 使用AccountID属性创建一些接口:

public interface IAccount
{
    int AccountID { get; set; }
}

And make User entity, Transaction entity, and Product entity implement it: 并使用户实体,交易实体和产品实体实现它:

public class User : IAccount
{
    public int AccountID { get; set; }
    // ... 
}

Then make constraint on generic type parameter : 然后对泛型类型参数进行约束

public void CheckForAccountAuthorization<T>(IQueryable<T> accounts)
   where T : IAccount
{
    IEnumerable<string> accountIdList 
        = accounts.Select(u => u.AccountID).Distinct();

    // ...
}

Now you have AccountID property available. 现在您有AccountID属性可用。

Use an interface: 使用界面:

interface IAccountable
{
    public int AccountID {get;}
}

Then specify it in the generic: 然后在泛型中指定它:

public void CheckForAccountAuthorization<T>(IQueryable<T> entityWithAccountIdProperty)
    where T : IAccountable
{
    IEnumerable<string> accountIdList 
        = entityWithAccountIdProperty.Select(u => u.AccountID).Distinct();

    //Do More Work...

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM