代码之家  ›  专栏  ›  技术社区  ›  frosty

如何在C中强制转换对象以获取ID#

  •  1
  • frosty  · 技术社区  · 15 年前

    我正在使用nhibernate,当某些对象为空时会出现问题。工业工程

    Region为空,当我转到userprofile.region.id时得到一个空引用

    当然,在我的应用程序中,我可以做一些像

    var regionId = (Model.UserProfile.Region != null) ? Model.UserProfile.Region.Id : 0);
    

    但我认为理想情况下我希望空对象ID等于0。

    这是可以实现的吗?这是可取的吗?

    阶段2使用接口

    我现在有:

       interface IEntity
        {
            int GetIdOrZero();
        }
    

    public class Region :IEntity
        {
    
            public virtual int Id { get; set; }    
    
            public int GetIdOrZero()
            {
                return (this != null) this.Id : 0;
            }
        }
    

    测试区域是否为空的最佳方法是什么?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Tim Robinson    15 年前

    不能更改空引用的行为,但可以定义一个扩展方法来执行您想要的操作:

    public static class RegionExtensions
    {
        public static int GetIdOrZero(this Region region)
        {
            return region == null ? 0 : region.Id;
        }
    }
    

    编辑:

    public interface IEntity
    {
        int Id { get; }
    }
    
    public class Region : IEntity { ... }
    
    public static class EntityExtensions
    {
        public static int GetIdOrZero(this IEntity entity)
        {
            return entity == null ? 0 : entity.Id;
        }
    }