C# 转换函数<;T1,bool>;to Func<;T2,bool>;
我有DTO和POCO,我使用C# 转换函数<;T1,bool>;to Func<;T2,bool>;,c#,func,C#,Func,我有DTO和POCO,我使用Func表示“where”。DTO和POCO实体具有相同的属性(属性的名称和类型) 我已经设法使用ExpresionsVisitor类将DTO表达式转换为POCO表达式 我使用表达式包括相关实体(entity.include)和Func作为where 下面有一个代码示例,我需要关于实现Translate方法的帮助 我该怎么做 public class Program { static void Main(string[] args)
Func
表示“where”。DTO和POCO实体具有相同的属性(属性的名称和类型)
我已经设法使用ExpresionsVisitor类将DTO表达式转换为POCO表达式
我使用表达式包括相关实体(entity.include)和Func作为where
下面有一个代码示例,我需要关于实现Translate方法的帮助
我该怎么做
public class Program
{
static void Main(string[] args)
{
ADTO a = new ADTO
{
Id = 1,
Name = "Test"
};
Func<ADTO,bool> dtoFunc = (dto => dto.Id == 1);
Func<A, bool> func = Translate(dtoFunc);
}
private static Func<A, bool> Translate(Func<ADTO, bool> dtoFunc)
{
// Implementation here
throw new NotImplementedException();
}
}
public class A
{
public int Id { get; set; }
public String Name { get; set; }
}
public class ADTO
{
public int Id { get; set; }
public String Name { get; set; }
}
公共类程序
{
静态void Main(字符串[]参数)
{
ADTO a=新ADTO
{
Id=1,
Name=“测试”
};
Func dtoFunc=(dto=>dto.Id==1);
Func Func=翻译(dtoFunc);
}
专用静态Func Translate(Func-dtoFunc)
{
//在这里实现
抛出新的NotImplementedException();
}
}
公共A类
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
公共类广告
{
公共int Id{get;set;}
公共字符串名称{get;set;}
}
您不能“翻译”函数。由于强类型,您需要实现它。
您需要的是将ADTO翻译成a,这很简单:
private A Translate(ADTO adto)
{
return new A() { Id = adto.Id, Name = adto.Name);
}
然后你需要了解你实际上在做什么。“函数”是对数据的执行,而不是数据本身。因此,您需要两个实现,但它们是相同的:
Func<A, bool> funcA = (a => a.Id == 1);
Func<ADTO, bool> funcADTO = (adto => adto.Id == 1);
我的建议是采用抽象版本,它有几个优点。
此时,您可以执行以下操作:
Func<AbstractDataTransferObject, bool> f = (adto => adto.Id == 1);
实现通用存储库时的最后一个问题是过滤器谓词的注入。指向解决方案的指针是谓词实际上是这样的:
Func<bool, T>
通用存储库将是:
Repository<Customer>
在某种程度上,当您拥有
AbstractFactory
、Repository
和AbstractDomainObject
将公共类ADTO
更改为公共类ADTO:A
时,协方差和逆变变得非常复杂,您就完成了;)您能以任何方式将A转换为ADTO吗?(我的意思是,不需要手动将值从一个值重新分配到另一个值)支持隐式或显式强制转换?为什么不直接复制属性?似乎微不足道。你不能这样做一定有原因。如果你在使用EF,你不应该使用表达式
?你为什么要谈论表达式,但在代码中使用编译函数?@Olinad你可以使用表达式
,并在需要时将其编译为函数
。你知道我想要什么。我已经有了一个抽象的传输类,它定义了我的传输层中暴露于wcf层CRUD操作的行为和外观接口。如果我理解正确,我就不能有通用的Func翻译程序了?我必须在两侧都有专门的、、where“”函数实现?例如,我的Facade interf中的GetAllById、GetAllByName?你能更具体地说明你在项目中是如何做到这一点的吗?很好的方法。但我必须这样做。我的通用数据应用程序层更像这样:。
SELECT * FROM Customers WHERE Age >= @minimumAge;
Func<bool, T>
Func<bool, Customer>
Repository<Customer>
public abstract class AbstractDomainObject
{
private int _id = -1;
public int ID
{
get
{
if (_id == -1)
{
throw new InvalidOperationException("domain object not yet persisted");
}
return _id;
}
set
{
if (_id != -1)
{
throw new InvalidOperationException("domain object already persisted");
}
_id = value;
}
}
public bool IsPersisted
{
get
{
return _id != -1;
}
}
}