作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想比较两个看起来像这样的类
public class Order
{
public string KundNummer, KundNamn, ErReferens, VarReferens, KontraktsNummer, Betvillk, Levvillk, Levsatt, Speditor,
Resenh, Projekt, OrderDatum, LeveransDatum, ErtOrdernr, LagerbokfDatum, KundPostAdr, KundPostAdr2, KundGLN, KundPostnr,
KundOrt, KundLandKod, KundLand, KundVATnr, KundDistrikt, KundSaljare, KundText1, KundText2, KundText3, KundSprak,
KundValuta, KundRabattAvtal, KundRabattAvtalBenamning, KundPrislista, KundPrislistaBenamning, KundALnamn, KundALpostAdr, KundALpostAdr2, KundALGLN, KundALpostnr, KundALort,
KundALlandKod, KundALland;
public double OrderNummer, Fakturarabatt, Frakt, Expavg, Brutto, Netto, ExklMoms, Totalt, Moms, Avrundn, KundValutaKurs, KundValutaEnhet;
public int EUPeriodSamman, InklMoms, EjKlar, Levererad, Malukerad, BestallningSkapad, Ordererk,
Plocklista, Foljesedel, ExtraOrderdokument, Restorder, Faktura, KundSparaText, KundExport, KundRantefakturering, KundKravbrev,
KundKravavgift, KundRestnoteraEj, KundSamlingsfakturera;
}
我想比较这个类的两个对象,以记录我的数据库中哪些字段发生了变化。
public string OrderUppdateraOrder(Order order)
{
Order OrderToCompare = new Order();
OrderToCompare = OrderVisaOrderInformation(order.OrderNummer);
//then the code goes on to make the changes to the database from the class order
//while OrdertoComapre still have the values from before this function was called
}
那么是否可以循环遍历这些类并比较它们,还是我必须为类中的每个变量编写一个if? :)
或者将其转换为列表?我不知道? :P
谢谢解答
最佳答案
i want to log if there is a difference and log the difference something like this CustomerNumber: changed from 456 to 345
最好的选择可能只是使用反射来爬过公共(public)属性和字段,比较它们。这将有更少的代码进行比较,但会有性能开销。您可以使用 FastMember 等工具大大减少开销:
static class Program {
static void Main()
{
Order o1 = new Order { Resenh = "abc" },
o2 = new Order { Resenh = "abc" };
ShowDiffs(o1, o2); // {nothing}
o2.Resenh = "def";
ShowDiffs(o1, o2); // Resenh changed from abc to def
}
static void ShowDiffs<T>(T x, T y)
{
var accessor = TypeAccessor.Create(typeof(T));
if (!accessor.GetMembersSupported) throw new NotSupportedException();
var members = accessor.GetMembers();
foreach (var member in members)
{
object xVal = accessor[x, member.Name],
yVal = accessor[y, member.Name];
if (!Equals(xVal, yVal))
{
Console.WriteLine("{0} changed from {1} to {2}",
member.Name, xVal, yVal);
}
}
}
}
关于c# - 遍历包含变量的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13490320/
我是一名优秀的程序员,十分优秀!