domainobjectidsetter.cs

来自「NHibernate简单DEMO」· CS 代码 · 共 33 行

CS
33
字号
using System.Reflection;
using BasicSample.Core.Domain;
using BasicSample.Core.Utils;

namespace BasicSample.Tests.Domain
{
    /// <summary>
    /// I've gone back and forth as to when it is appropriate to use reflection for 
    /// accessing/setting a private/protected members.  It is imperitive that the <see cref="DomainObject{IdT}.ID"/>
    /// property is read-only and set only by the ORM.  With that said, some unit tests need 
    /// ID set accordingly; therefore, this utility enables that ability.  This class should 
    /// never be used outside of the unit tests.  Instead, implement <see cref="IHasAssignedId{IdT}" /> to 
    /// expose a public setter.
    /// </summary>
    public class DomainObjectIdSetter<IdT>
    {
        /// <summary>
        /// Uses reflection to set the ID of a <see cref="DomainObject{IdT}" />.
        /// </summary>
        public void SetIdOf(DomainObject<IdT> domainObject, IdT id) {
            // Set the data property reflectively
            PropertyInfo idProperty = domainObject.GetType().GetProperty(NAME_OF_ID_MEMBER, 
                BindingFlags.Public | BindingFlags.Instance);

            Check.Ensure(idProperty != null, "idProperty could not be found");

            idProperty.SetValue(domainObject, id, null);
        }

        private const string NAME_OF_ID_MEMBER = "ID";
    }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?