C#通用传递具有相同属性的不同对象 [英] C# Generic Passing different objects with same properties

查看:20
本文介绍了C#通用传递具有相同属性的不同对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定我正在做的事情是否可行.我有两种方法.这两个方法的主体完全相同,但是方法的参数和返回的签名不同.传入参数的属性发生变化,对象不同但属性名称相同(它们是两个不同的实体框架实体).从基础对象继承两者是不可能的(我认为),因为它们是实体框架实体.

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..

方法一

private static IQueryable<MapListing> ApplyMapFilterToListings(IQueryable<MapListing> listings, ListingSearchCriteria criteria, bool boolIsPremiumListingsOnly = false)
{
    //setting properties of listings (of type MapListing Entity)
}

方法二

private static IQueryable<vListing> ApplyFilterToListings(IQueryable<vListing> 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.

我重新使用 IQueryable<> 的另一个原因是因为我在返回后对它做了其他事情

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

推荐答案

在我看来你有两个选择.

You have two options in my opinion.

  1. 实现一个接口

如果您创建一个包含所有共享属性和方法的接口,您可以创建一个接受该接口的方法,或者在使用泛型时,所有实现它的类型.(是的,可以在 EF 生成的类中实现接口)

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)

使用动态

dynamic 关键字会给你很大的自由度.您可以假装某个属性或方法是否存在.当您传入对象时,会在运行时检查这一点.您应该谨慎使用 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.

首选第一个选项.这是最好的解决方案,但它要求您可以访问这些类.如果类在第三方库中,dynamic 可能是您唯一的解决方案.

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.

这篇关于C#通用传递具有相同属性的不同对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆