嗨,我有一个问题,我已经黑了几个小时,我一直收到错误
无法将属性或索引器'AnonymousType#1.XP'分配给它 是只读的
问题发生在这里的a.XP
foreach (var a in comments)
{
a.XP = score.getLevel(a.XP);
}
并且作为评论指出我从未说过我想做什么,我想用改进的值得分替换a.XP.getLevel(a.XP)。
这是完整的代码
protected void GetComments()
{
TimberManiacsDataContext db = new TimberManiacsDataContext();
Score score = new Score();
var comments = (from fComment in db.Comments
where fComment.PublishID == Convert.ToInt32(Request.QueryString["Article"])
orderby fComment.DateTime descending
select new
{
UserName = fComment.User.UserLogin.Username,
PostTime = fComment.DateTime,
UserImage = fComment.User.UserGeneralInfo.ProfilePicture,
Comment = fComment.Comment1,
UserID = fComment.UserID,
XP = fComment.User.CommunityScore
}).Take(10).ToList();
foreach (var a in comments)
{
a.XP = score.getLevel(a.XP);
}
Commentlist.DataSource = comments;
Commentlist.DataBind();
}
答案 0 :(得分:12)
匿名类型的对象是只读的,但是根据您的代码示例,几乎不需要在循环中尝试此修改,只需将其作为查询执行的一部分。
XP = score.getLevel(fComment.User.CommunityScore)
如果在执行查询后发现自己需要执行更改,那么您应该继续定义一个允许此类突变的类,然后选择该类而不是匿名类型。
class CommentData { ... } // define this type with your properties
// then use it for the query projection
select new CommentData
{
// ...
}
答案 1 :(得分:7)
C#中的匿名类型是不可变的,你无能为力。在我看来,你有两个选择:
XP
。将旧对象的内容复制到新对象中,XP
除外:
var modifiedComments = comments.Select(
c => new
{
c.UserName,
c.PostTitle,
c.UserImage,
c.Comment,
c.UserID,
XP = score.getLevel(c.XP)
});