gpt4 book ai didi

c# - 从 'empty' 控件中为变量赋值,一定有更好的方法!

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:53 24 4
gpt4 key购买 nike

我有一个供内部使用的 winform 应用程序,其中以下情况很常见。

            Int32? afhAgreement = null;
if (!lkuReveiewAFHAgreement.Text.Equals(string.Empty))
{
afhAgreement = (Int32)lkuReveiewAFHAgreement.EditValue;
}
DateTime? afhAgreementDate = null;
if (datAFHAgreementCompleted.Text != String.Empty)
{
afhAgreementDate = (DateTime?)datAFHAgreementCompleted.EditValue;
}
Int32? crisisPlan = null;
if (!lkuReview6MonthCrisisPlan.Text.Equals(string.Empty))
{
crisisPlan = (Int32)lkuReview6MonthCrisisPlan.EditValue;
}
DateTime? crisisPlanDate = null;
if (dat6MonthCrisisPlanReviewed.Text != String.Empty)
{
crisisPlanDate = (DateTime?)dat6MonthCrisisPlanReviewed.EditValue;
}
Int32? riskAgreement = null;
if (!lkuReviewRiskAssessment.Text.Equals(string.Empty))
{
riskAgreement = (Int32)lkuReviewRiskAssessment.EditValue;
}
DateTime? riskAgreementDate = null;
if (!datRiskAssessmentReviewed.Text.Equals(string.Empty))
{
riskAgreementDate = (DateTime?)datRiskAssessmentReviewed.EditValue;
}

鉴于所有这些变量都可以是 NULL,这似乎是一种荒谬的方法。不是有Convert this object and Default to NULL吗?

顺便说一句,EditValue 是一个对象,但我相信即使我使用控件的 Text 属性也会遇到同样的问题。

那么,有没有更好的办法呢?这是我可以使用 Extension Methods 简化的东西吗?

最佳答案

只需添加一些可重用的函数...例如:

static T? GetValue<T>(YourControlType control) where T : struct
{
if (string.IsNullOrEmpty(control.Text)) return null;
return (T)control.EditValue;
}

然后(例如):

DateTime? crisisPlanDate = GetValue<DateTime>(dat6MonthCrisisPlanReviewed);

(其中 YourControlType 是您使用 string .Textobject .EditValue 的任何控件)

关于c# - 从 'empty' 控件中为变量赋值,一定有更好的方法!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2288721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com