c# - 错误不能在此上下文中使用属性或索引器,因为设置访问器不可访问

标签 c#

我有以下代码:

using System;
using System.Collections.Generic;
using System.Text;
using ProjectBase.Utils;

namespace EnterpriseSample.Core.Domain
{
    public class Notifikasi : DomainObject<string>, IHasAssignedId<string>
    {
        public string Name { get; set; }
        public string Description { get; set; }
        public DateTime StartDate { get; set; }
        public DateTime EndDate { get; set; }
        public DateTime CreatedDate { get; set; }
        public string CreatedBy { get; set; }
        public DateTime UpdateDate { get; set; }
        public string UpdateBy { get; set; }

        public void SetAssignedIdTo(string assignedId)
        {
            Check.Require(!string.IsNullOrEmpty(assignedId), "assignedId may not be null or empty");

            // As an alternative to Check.Require, which throws an exception, the 
            // Validation Application Block could be used to validate the following
            Check.Require(assignedId.Trim().Length == 5, "assignedId must be exactly 5 characters");

            ID = assignedId.Trim().ToUpper();
        }

        public override int GetHashCode()
        {
            return (GetType().FullName + "|" +
                    ID + "|" +
                    Name).GetHashCode();

        }
    }
}

我在不同的类中使用了 Notifikasi 类,但是 oNoti.ID = "12"; 产生了一个错误:

The property or indexer cannot be used in this context because the set accessor is inaccessible.

谁能帮我解决这个问题? (如果相关,我会使用 ORM)。

INotifikasiDao dao = DaoFactory.GetNotifikasiDao();

dao.closeSession();
dao.openSession();
EnterpriseSample.Core.Domain.Notifikasi oNoti = new EnterpriseSample.Core.Domain.Notifikasi();
int no = 1;
oNoti.Name = "ETL Account History";
DateTime startDate = DateTime.Today;
DateTime expiryDate = startDate.AddDays(30);
oNoti.StartDate = startDate;
oNoti.EndDate = expiryDate;
oNoti.Description = "ACC_HIST" + startDate + "Failure";
oNoti.ID = "12"; //this is where the error happens

dao.Update(oNoti);

最佳答案

您的问题缺少DomainObject 的重要定义,但错误消息表明属性ID 是这样声明的:

public string ID
{
    get;
    protected set;
}

这意味着 ID 的值可以被任何人读取,但它只能从 DomainObject 和派生类的实例内部设置。

使用 SetAssignedIdTo 也不是一个选项,因为它需要 5 个字符,您要分配的 ID 只有两个字符长。我假设存在此方法是为了能够手动将 ID 分配给通常具有自动递增键的表中的行。强制此 ID 使用 5 个字符可确保 - 在某种程度上 - 手动分配的 key 不会与自动创建的 key 冲突。

关于c# - 错误不能在此上下文中使用属性或索引器,因为设置访问器不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14455213/

相关文章:

c# - 如何编写为模板化基指定类型参数的派生类

c# - 证书的私钥导出为不同的值?

javascript - C# 如何将复杂的 JSON 对象的子对象转换为模型

c# - 使用c#并行下载多个文件

c# - 预期的方法名称?

c# - 强制转换以从所选中获取 ID 不起作用

c# - TSQL 从列可能不存在的临时表插入

c# - 从异常详情中获取异常发生的类名和方法名

c# - 如何使用C#为sql server的表添加一列?

c# - 如何加入新指南列表?