C# - Passing the object type in a method parameter
我正在尝试将对象类型传递给方法。我正在为我的CRUDRepository执行此操作,该CRUDRepository由其他存储库继承,但是我不知道如何知道我正在处理的类型。
例如:
1 2 3 4
| public PageOf<Entity> GetPageOfEntity(int pageNumber, int pageSize)
{
// Here i need to work with the entity type to make calls to database
} |
实体是由其他实体(用户,产品等)继承的对象,并且此方法返回分页结果。我这样做是为了避免为我拥有的每个实体创建GetPageOf方法。
将要处理分页结果的对象类型传递给方法的正确方法是什么?
编辑:
这是实体的一个例子
1 2 3 4 5
| public abstract class Entity
{
public virtual long Id { get; set; }
public virtual DateTime Created { get; set; }
} |
和用户对象:
1 2 3 4
| public class User : Entity
{
public string FirstName { get; set; }
} |
当我试图编写单个类来处理某些操作时,我需要在方法中知道我正在使用的对象(但是我现在想为每种对象类型创建一个方法)
谢谢
- 多一点代码
-
使方法通用:
1 2 3 4 5 6
| public PageOf <TEntity > GetPageOfEntity <TEntity >(int pageNumber, int pageSize )
where TEntity : Entity
{
Type entityType = typeof(TEntity );
...
} |
434511
我不确定,我正确理解了您的问题,但是您不能只使用通用参数吗?
1 2 3 4 5
| public PageOf<Entity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize)
where TEntity : Entity
{
// Here i need to work with the entity type to make calls to database
} |
-
使方法通用:
1 2 3 4 5 6
| public PageOf <TEntity > GetPageOfEntity <TEntity >(int pageNumber, int pageSize )
where TEntity : Entity
{
Type entityType = typeof(TEntity );
...
} |
434511
我不确定,我正确理解了您的问题,但是您不能只使用通用参数吗?
1 2 3 4 5
| public PageOf<Entity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize)
where TEntity : Entity
{
// Here i need to work with the entity type to make calls to database
} |
-
使方法通用:
1 2 3 4 5 6
| public PageOf <TEntity > GetPageOfEntity <TEntity >(int pageNumber, int pageSize )
where TEntity : Entity
{
Type entityType = typeof(TEntity );
...
} |
434511
我不确定,我正确理解了您的问题,但是您不能只使用通用参数吗?
1 2 3 4 5
| public PageOf<Entity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize)
where TEntity : Entity
{
// Here i need to work with the entity type to make calls to database
} |
使方法通用:
1 2 3 4 5 6
| public PageOf <TEntity > GetPageOfEntity <TEntity >(int pageNumber, int pageSize )
where TEntity : Entity
{
Type entityType = typeof(TEntity );
...
} |
- 谢了哥们。我将阅读有关通用方法和类的文章,以了解其工作原理。
-
您是否还不需要TEntity类型的参数来获取页面?
-
@Phil:不,但是在那种情况下您不能使用类型推断。只要您明确指定类型参数,就可以了。
我不确定,我正确理解了您的问题,但是您不能只使用通用参数吗?
1 2 3 4 5
| public PageOf<Entity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize)
where TEntity : Entity
{
// Here i need to work with the entity type to make calls to database
} |
-
抱歉,我的英语不完美(我是葡萄牙语),有时我真的无法表达自己的意思!但是,是的,我需要通用参数。谢谢 ;)