检查属性是类型还是可空类型

时间:2018-08-13 03:48:28

标签: c# reflection

我目前正在检查属性类型是DateTime还是可为空的DateTime,如下所示:

            public class PXAddAtttributeColumns : CRAttributesFieldAttribute
              {
                string[] _names;

                public PXAddAtttributeColumns(string[] names, Type classID, 
                  Type noteID)
                   : base(classID, noteID)
                {
                       _names = names;
                }

        public override void CacheAttached(PXCache sender)
        {
            this._IsActive = true;
            base.CacheAttached(sender);
        }

        protected override void AttributeFieldSelecting(PXCache sender, PXFieldSelectingEventArgs e, PXFieldState state, string attributeName, int idx)
        {
            if (_names.Any(attributeName.Equals))
            {
                state.DisplayName = (!String.IsNullOrEmpty(state.DisplayName)) ? (state.DisplayName.Replace("$Attributes$-", "")) : attributeName;
                state.Visible = true;
                state.Visibility = PXUIVisibility.Dynamic;
            }

            base.AttributeFieldSelecting(sender, e, state, attributeName, idx);
        }
    }

       public class InventoryItemExt : PXCacheExtension<PX.Objects.IN.InventoryItem>
       {

              public abstract class itemAttributes : IBqlField { }

               [InventoryItemMaint_Extension.PXAddAtttributeColumns(new[] { 
                                       "COLOR" },
                                        typeof(InventoryItem.itemClassID),
                                        typeof(InventoryItem.noteID))]
               public virtual string[] ItemAttributes { get; set; }

       }

有人可以告诉我是否可以通过检查基础类型将其浓缩为一个语句吗?

3 个答案:

答案 0 :(得分:2)

这是一个简单的解决方案:typeof(DateTime?).IsAssignableFrom(prop.PropertyType)。对于DateTime?DateTime,这将是 true ,对于其他人,这将是 false

答案 1 :(得分:0)

您可以尝试以下方法:

if (prop.PropertyType.UnderlyingSystemType==typeof(DateTime))

...

答案 2 :(得分:0)

尝试类似的方法

new Container(
                    padding: EdgeInsets.fromLTRB(350.0, 20.0, 0.0, 0.0),
                    child: new IconButton(
                        icon: new Icon(Icons.delete), onPressed: () {}),
                  ),

输出:public class Program { public static void Main(string[] args) { //Your code goes here DateTime? nullableDate = null; bool output = CheckNull.IsNullable(nullableDate); // false Console.WriteLine(output ); } public static class CheckNull { public static bool IsNullable<T>(T t) { return false; } public static bool IsNullable<T>(T? t) where T : struct { return true; } } }