java implement 泛型,C#泛型传递不同的对象具有相同的属性

这篇博客探讨了在两个方法体相同但参数和返回类型不同的方法中,如何通过实现接口或使用动态类型来避免代码重复。作者提出了两种解决方案:一是创建一个包含共享属性和方法的接口,让实体框架实体类实现该接口;二是使用动态类型来处理对象。尽管动态类型提供了灵活性,但作者倾向于使用接口,因为这更有利于代码维护和类型安全性,特别是在涉及大量条件属性设置时。
摘要由CSDN通过智能技术生成

I am not sure if what I am doing is possible.

I have 2 methods. The body of the 2 methods are exactly identical, however the signature of the method both parameter and return are different. The passed in parameter's properties are changed and the object are different but have the same property name (They are two different Entity Framwork Entities). Inheriting both from a base object is not possible (i think) because these are Entity Framework Entities.

Best to show example then talk about it..

Method 1

private static IQueryable ApplyMapFilterToListings(IQueryable listings, ListingSearchCriteria criteria, bool boolIsPremiumListingsOnly = false)

{

//setting properties of listings (of type MapListing Entity)

}

Method 2

private static IQueryable ApplyFilterToListings(IQueryable listings, ListingSearchCriteria criteria, bool boolIsPremiumListingsOnly = false)

{

//setting properties of listings (of type vListing Entity)

}

Generally I would not mind if the body of the function is exactly identical, however in this case a lot of properties are set conditionally and I want to make these methods exactly identical and idiot proof that they go out of sync.

Also reason I am returing IQueryable<> is because I do other stuff to it after returning

解决方案

You have two options in my opinion.

Implement an interface

If you create an interface containing all shared properties and methods, you can create one method accepting that interface, or when using generics, all types implementing it. (Yes, it is possible to implement an interface in EF generated classes)

Use dynamic

The dynamic keyword will give you a lot of freedom. You can pretend if a property or method exists. This is checked at runtime when you pass in the object. You should use dynamic with care, since it can harm your software quality.

The first option is preferred. It is the best solution, but it requires you to have access over the classes. If the classes are in a third party library, dynamic is probably your only solution.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值