English 中文(简体)
使用通用标识
原标题:Using generic func signature

我只想在记忆库中执行一个简单(仅测试目的)如下。 它使用的接口是通用的。 下面的样本代码中使用了“填写”方法之一。

上游的投放是一种例外。 我如何正确执行删除的方法?

public class InMemoryReportingRepository : IReportingRepository
{
    private readonly List<IDto> m_dtos;

    public InMemoryReportingRepository()
    {
        m_dtos = new List<IDto>();
    }

    // ommitted stuff

    public void Delete<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, IDto
    {
        var delete = m_dtos.FirstOrDefault((Func<IDto, bool>) predicate.Compile());

        m_dtos.Remove(delete);
    }
}
最佳回答

如下:

public void Delete<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, IDto
{
    var compiled = predicate.Compile();
    var toDelete = m_dtos.FirstOrDefault(dto => (dto is TEntity) && compiled((TEntity)dto));
    m_dtos.Remove(delete);
}

<代码>Func<TEntity, bool>和Func<IDto, bool>完全不同类型,这就是为什么你的投放失败的原因。

不过,我建议使用门级通用值,用于你的记忆数据储存:

public class DataStore<TEntity> : IDataStore<TEntity> where TEntity : class, IDto
{
  private readonly List<TEntity> m_dtos = new List<TEntity>();
  ...
  public void Delete(Func<TEntity, bool> predicate)
  {
    var toDelete = m_dtos.FirstOrDefault(predicate);
    m_dtos.Remove(toDelete);
  }
}
问题回答
public void Delete<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : class, IDto

1. 采用<代码>TEntity的基数表示,其中TEntity为参照型,实施IDto<>code>。

(Func<IDto, bool>) predicate.Compile();

标注如下:Func<IDto, bool>,不是什么。

There s a few variants on just what you want here, but I suspect that:

public void Delete<TEntity>(Expression<Func<IDto, bool>> predicate) where TEntity : class, IDto

Will give you what you need.





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...