无法使用Enums隐式转换类型

时间:2013-10-09 14:40:27

标签: c# asp.net-mvc asp.net-mvc-4 enums

尝试解决此问题。似乎无法将一个num分配给另一个,即使它们实际上是相同的。

  

无法将类型'Project.Models.Concern.YesNo'隐式转换为   'Project.ViewModels.PatientConcernsViewModel.YesNo'。一个明确的   存在转换(你错过了演员吗?)

public class Concern
{
    public int ConcernID { get; set; }
    public YesNo LifeExpectancy { get; set; }
    public YesNo CollateralHistoryAvailable { get; set; }

    public enum YesNo
    {
        Yes,
        No
    }
}

public class PatientConcernsViewModel
{
    public int ConcernID { get; set; }

    public YesNo LifeExpectancy { get; set; }        
    public YesNo CollateralHistoryAvailable { get; set; }

    public enum YesNo
    {
        Yes,
        No
    }
}

// FROM WITHIN MY CONTROLLER

var concern = concernRepository.Find(id);

// load related assessment data
var assessment = assessmentRepository.Find(AssessmentID);

PatientConcernsViewModel patientConcernsViewModel = new PatientConcernsViewModel();

// BOTH LINES BELOW GENERATE ERRORS            
patientConcernsViewModel.CollateralHistoryAvailable = concern.CollateralHistoryAvailable;
patientConcernsViewModel.LifeExpectancy = concern.LifeExpectancy;

4 个答案:

答案 0 :(得分:5)

在没有课程的情况下让您的enum公开 - 然后他们可以在没有多个定义的情况下分享它。

public enum YesNo
{
    Yes,
    No
}

public class Concern
{
    public int ConcernID { get; set; }
    public YesNo LifeExpectancy { get; set; }
    public YesNo CollateralHistoryAvailable { get; set; }
}

public class PatientConcernsViewModel
{
    public int ConcernID { get; set; }

    public YesNo LifeExpectancy { get; set; }        
    public YesNo CollateralHistoryAvailable { get; set; }
}

答案 1 :(得分:5)

删除YesNo枚举,并将其替换为System.Boolean。尽可能使用系统类型。

public class Concern
{
    public int ConcernID { get; set; }
    public bool LifeExpectancy { get; set; }
    public bool CollateralHistoryAvailable { get; set; }
}

public class PatientConcernsViewModel
{
    public int ConcernID { get; set; }

    public bool LifeExpectancy { get; set; }        
    public bool CollateralHistoryAvailable { get; set; }

}

答案 2 :(得分:0)

为什么不限制YesNo枚举以便两者都访问同一个对象?

public enum YesNo
{
    Yes,
    No
}

public class Concern
{
    public int ConcernID { get; set; }
    public YesNo LifeExpectancy { get; set; }
    public YesNo CollateralHistoryAvailable { get; set; }
}

public class PatientConcernsViewModel
{
    public int ConcernID { get; set; }

    public YesNo LifeExpectancy { get; set; }        
    public YesNo CollateralHistoryAvailable { get; set; }

}

答案 3 :(得分:0)

您有2个完全不同的枚举,恰好在完全限定名称中具有相同的项目和相同的最后一个单词。

如错误所述,您有Project.Models.Concern.YesNoProject.ViewModels.PatientConcernsViewModel.YesNo

如果你只是把你的枚举放在其他地方更合适,那么这两个类都可以使用它而你没有2种类型。

虽然上面回答了你的问题,但Aron表示,对于我能想象的几乎所有目的来说,bool会比Yes / No枚举更好。