简体   繁体   English

是否有可能通过c#中的值获取属性

[英]is it possible to get a property by its value in c#

I have this code where I compare the values of oldState object by the currentState in fluent inhibernate, what I want is to log the property that has been changed and its value,here I get the new and the old values but I waant also to get the property name. 我有这段代码,我在流利的休眠状态下通过currentState比较oldState对象的值,我想要的是记录已更改的属性及其值,在这里我得到了新的和旧的值,但我也想得到属性名称。

if I reflect @event.Entity I can get all the properties and their values so is there any way to get the property name by its value. 如果我反映@event.Entity ,则可以获取所有属性及其值,因此有任何方法可以通过其值获取属性名称。

public void OnPostUpdate(NHibernate.Event.PostUpdateEvent @event)
{
    var entityToAudit = @event.Entity as IAuditable;
    string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AuditLog.txt");
    using (StreamWriter sw = File.AppendText(path))
    {
        for (int i = 0; i < @event.OldState.Length; i++)
        {
            if (@event.OldState[i] != null)
            {
                if (!@event.OldState[i].Equals(@event.State[i]))
                {
                    sw.WriteLine("the value has ben changed from " + @event.OldState[i] + " to " + @event.State[i]);
                }
            }
            else
            {
                if (@event.State[i] != null)
                {
                    sw.WriteLine("the value has ben changed from being empty to " + @event.State[i]);
                }
            }
        }
    }
}

You don't need to use System.Reflection for that. 您不需要为此使用System.Reflection PostUpdateEvent already contains all the property names in the order you need : PostUpdateEvent已经按您需要的顺序包含了所有属性名称:

var propertyName = e.Persister.PropertyNames[i];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM