无法将类型“ System.DateTime”隐式转换为“ LearnScan.LearnUser.NullableDateTime”

时间:2019-05-10 15:01:58

标签: c# asp.net .net datetime nullable

尝试为创建用户肥皂呼叫设置值,以及在为新用户设置开始日期时:

DateTime? dt = DateTime.Now;
emptyUsr.StartDate = dt;

它返回错误“无法将类型'System.DateTime'隐式转换为'LearnScan.LearnUser.NullableDateTime'”。我的印象是DateTime?设置为可空?

StartDate属性的类型为LearnScan.LearnUser.NullableDateTime,定义为:

public partial class NullableDateTime : object, System.ComponentModel.INotifyPropertyChanged {
    internal static object DateTime;
    private bool isNullField;

    private System.DateTime valueField;

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=0)]
    public bool IsNull {
        get {
            return this.isNullField;
        }
        set {
            this.isNullField = value;
            this.RaisePropertyChanged("IsNull");
        }
    }

    /// <remarks/>
    [System.Xml.Serialization.XmlElementAttribute(Order=1)]
    public System.DateTime Value {
        get {
            return this.valueField;
        }
        set {
            this.valueField = value;
            this.RaisePropertyChanged("Value");
        }
    }

    public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;

    protected void RaisePropertyChanged(string propertyName) {
        System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
        if ((propertyChanged != null)) {
            propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
        }
    }
}

*解决方案-它需要每个emptyUsr.StartDate.IsNull = falseemptyUsr.StartDate.Value= DateTime.Now;的值

2 个答案:

答案 0 :(得分:2)

您可以创建从DateTime?到您的NullableDateTime类的隐式转换:

namespace LearnScan.LearnUser {
    public partial class NullableDateTime
    {
        public static implicit operator NullableDateTime(DateTime? dt)
        {
            if(dt.HasValue)
            {
                return new NullableDateTime { IsNull = false, Value = dt.Value };
            }
            else
            {
                 return new NullableDateTime { IsNull = true };
            }
        }
    }
}

答案 1 :(得分:1)

NullableDateTime外部定义的类型(因为它不是常规C#库和API集的不是的一部分)与DateTime?不同。尽管其简短名称可能会引起您的思考,但其全名LearnScan.LearnUser.NullableDateTime告诉您它与System.DateTime?(在.NET中为DateTime?的实际全名)有很大不同。您需要了解如何实现NullableDateTime以及如何使用它。从注释中提供的简短片段开始,对基于.NET提供的DateTime结构构建的可为null的DateTime类型可能是一种不同的方法。