![](/img/trans.png)
[英]could not be set to a 'System.Decimal' value. You must set this property to a non-null value of type 'System.Double'
[英]Set a property to a non-null value of type 'System.Double'
如何解決此錯誤?
無法將“學生”的“ CreditsEarned”屬性設置為“空”值。 您必須將此屬性設置為'System.Double'類型的非空值。
這是我的代碼:
public class Student : Person
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Enrollment Date")]
public DateTime EnrollmentDate { get; set; }
// Credits earned
[Display(Name = "Credits Earned")]
public double CreditsEarned { get; set; }
// GPA
[Display(Name = "GPA")]
[Range(typeof(double), "0.7", "4.0")]
public double Gpa { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
請問為什么要將double類型設置為null?
默認情況下,C#中的double類型不為null。 您必須將其顯式設置為null。
[Display(Name = "Credits Earned")]
public double? CreditsEarned { get; set; }
在類型聲明之后注意問號。 在C#中,這告訴編譯器該類型可能被標記為可空。
編輯:
請查看以下鏈接:
1) C#中的可空類型
2) C#示例中的可空類型
使用Double?
(一個Double類型的ullable)已被提及,以允許該屬性保存空值。
另一種選擇是將屬性初始化為0,並確保它始終為0或其他數字。
public class Student : Person
{
// This will make sure the value is initially defined (to 0):
public Student(){
CreditsEarned = 0;
}
...
// Credits earned
[Display(Name = "Credits Earned")]
public double CreditsEarned { get; set; }
你應該試試
// Credits earned
[Display(Name = "Credits Earned")]
public double? CreditsEarned { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.