无法在C#类的实例上设置公共属性

时间:2017-01-05 18:16:11

标签: c# .net visual-studio visual-studio-2015 nspec

我正在尝试在移动服务应用程序中编写我的第一个NSpec测试。我在规范中创建了一个属性。但是当我尝试在下一行访问该元素时,我无法访问该实例上的公共属性,因为Visual Studio无法识别该变量。

AppointmentSpec.cs

public class AppointmentSpec : nspec
    {
        private AppointmentDTO _dto = new AppointmentDTO();
        _dto.PatientId = "124234"; // Visual Studio is not regonizing _dto

    }

AppointmentDTO.cs

public class AppointmentDTO
    {
        public string PatientId { get; set; }
       // public string PathwayId { get; set; }
        public string ItemId { get; set; }
        public string Subject { get; set; } //Dr. Visit, labtest, labtest name, follow up, other...
       // public string ProviderName { get; set; }
        public string Location { get; set; }  //clinic, hsopital name, etc
        public string Address { get; set; }  //street address
        public string PhoneNumber { get; set; }
        //to automatically add a corresponding appointment to the provider's calendar
        public bool SetProviderAppointment { get; set; }
        public string ProviderItemId { get; set; }
        public List<string> ProviderItemIds { get; set; } 
        public bool IsVideoCall { get; set; }
        public TimeSpan StartTime { get; set; }
        public TimeSpan EndTime { get; set; }

        public DateScheduleInfo EventDateSchedule { get; set; }

        //public TimeScheduleInfo EventTimeSchedule { get; set; }

        //public void Send(object target, string methodName, params object[] args)
        //{
        //    var properties = GetProperties(target.GetType());
        //    var property = properties.First(p => p.Name == methodName);
        //    if(property == null)
        //        throw new ArgumentException($"{target.GetType()} has no property or method ");
        //    property.SetValue(target, args.First());
        //}

        //private static IEnumerable<PropertyInfo> GetProperties(Type t)
        //{
        //    return t == null ? Enumerable.Empty<PropertyInfo>() : t.GetProperties().Union(GetProperties(t.BaseType));
        //}
    }

2 个答案:

答案 0 :(得分:4)

在类的构造函数中进行赋值:

public class AppointmentSpec : nspec
    {
        private AppointmentDTO _dto = new AppointmentDTO();

        public AppointmentSpec()
        {
            _dto.PatientId = "124234";
        }

    }

答案 1 :(得分:4)

您在无效的上下文中访问_dto。如果您打算使用某些数据初始化PatientId,请尝试以下操作:

private AppointmentDTO _dto = new AppointmentDTO
{
    PatientId = "124234"
};

请参阅MSDN