有人可以帮助我理解创建对象实例和在创建过程中传递值与创建对象然后设置属性之间的区别吗?
当我在对象创建上设置跟踪时,可以看到domainName
,id
和guid
进入了类,但是它完全绕开了guid
的设置。是因为我的SASReadToken值是'null'而停止了?
这有效:
TenantEntityModel tenantEntity = new TenantEntityModel
{
PartitionKey = domainName,
RowKey = id,
SASReadToken = null,
ApiKey = guid
};
TableOperation tableOperation = TableOperation.Insert(tenantEntity);
在创建过程中传递值会为guid
提供全零:
TenantEntityModel tenantEntity = new TenantEntityModel(domainName, id, null, guid);
TableOperation tableOperation = TableOperation.Insert(tenantEntity);
这是我的课程:
public class TenantEntityModel : TableEntity
{
public string SASReadToken { get; set; }
public Guid ApiKey { get; set; }
public TenantEntityModel(string TenantDomainName, string Id, string SASReadToken, Guid ApiKey)
{
this.PartitionKey = TenantDomainName;
this.RowKey = Id;
}
public TenantEntityModel() { }
}
答案 0 :(得分:4)
执行此操作时:
TenantEntityModel tenantEntity = new TenantEntityModel
{
PartitionKey = domainName,
RowKey = id,
ApiKey = guid
};
您正在有效地这样做:
TenantEntityModel tenantEntity = new TenantEntityModel();
tenantEntity.PartitionKey = domainName;
tenantEntity.RowKey = id;
tenantEntity.ApiKey = guid;
这不应与将参数传递给构造函数相混淆(在第二个示例中这样做)。您的构造函数对SASReadToken
和ApiKey
参数不做任何事情。这就是为什么它们被忽略的原因。
如果您希望构造函数完成这项工作,则需要类似以下内容:
public TenantEntityModel(string TenantDomainName, string Id, string SASReadToken, Guid ApiKey)
{
this.PartitionKey = TenantDomainName;
this.RowKey = Id;
this.SASReadToken = SASReadToken;
this.ApiKey = ApiKey;
}
答案 1 :(得分:1)
在TenantEntityModel(string, string, string, Guid)
的构造函数中,您没有将ApiKey
设置为任何值。试试这个:
public class TenantEntityModel : TableEntity
{
public string SASReadToken { get; set; }
public Guid ApiKey { get; set; }
public TenantEntityModel(string TenantDomainName, string Id, string SASReadToken, Guid ApiKey)
{
this.PartitionKey = TenantDomainName;
this.RowKey = Id;
this.SASReadToken = SASReadToken;
this.ApiKey = ApiKey;
}
public TenantEntityModel() { }
}
请注意,这段代码:new TenantEntityModel {...}
不是“将参数传递给构造函数” ,而是“使用默认值(无参数构造函数)并逐一设置属性”
备注:
对于我来说,我通常不通过构造函数使用可公开使用的setter来设置属性,因为您始终可以像在代码示例中那样进行操作:
var tenantEntity = new TenantEntityModel
{
PartitionKey = domainName,
RowKey = id,
SASReadToken = null,
ApiKey = guid
};
因此,如果您的PartitionKey
和RowKey
设置器是公开可用的(如我所见),则构造函数TenantEntityModel(string, string, string, Guid)
几乎没有用。