![](/img/trans.png)
[英]Can't access C# object properties returned from WebClient.UploadValues()
[英]How can i access the properties of a returned object in c#
在下面显示的代码中,“游戏”是“ Ilist”。(游戏Ilist)。 “主页”是Game类的属性,该类返回“ team”-这又是另一个具有Name属性的类。 名称返回字符串。 所以,如果我想将Name设置为某些字符串,如何访问Name的属性? 我尝试了Game.Home.Name =“ string”但不起作用
//public team Home{get; set;}
public class InsertGameCommand : DatabaseCommand
{
public DateTime Date { get; set; }
public string HomeTeamId { get; set; }
public string VisitorTeamId { get; set; }
public int HomeScore { get; set; }
public int VisitorScore { get; set; }
public string ParkId { get; set; }
public int Attendance { get; set; }
public override void Execute(Database db)
{
// could not access parkId and Home
db.Games.Add (new Game
{
Date = Date,
Home = HomeTeamId,
Visitor = VisitorTeamId,
HomeScore = HomeScore,
VisitorScore = VisitorScore,
Park = ParkId,
Attendance = Attendance
}
);
}
}
}
// game class
public class Game
{
public DateTime Date { get; set; }
public Park Park { get; set; }
// home class
public Team Home { get; set; }
}
//team class
public class Team
{
public League League { get; set; }
public string Name { get; set; }
}
首先,这是令人困惑的代码。
避免将这样的事情重命名为可读代码:
public Team Home { get; set; }
您的代码中存在多个错误(NullReference,CastingError,并且肯定会误解数据库的工作方式)以添加游戏:
db.Games.Add (new Game
{
Date = Date,
Home = HomeTeamId, // <-- Exception (string to Team class)
Visitor = VisitorTeamId, // <-- Property doesn't exists on Game class
HomeScore = HomeScore, // <--- Also not exists
VisitorScore = VisitorScore, // <--- missing
Park = ParkId, // <-- Exception (string to unknown class)
Attendance = Attendance // also not defined in your 'Game' Class
}
);
如何解开此spagetti代码? 简单易用的编码:
确保所有必需的属性都已在您的类中定义(用于访问)和初始化(防止NullReference错误) :
public class Game
{
public Game(string homeTeamId, string visitorTeamId)
{
// Default Constructor
GamePark = new Park();
HomeTeam = new Team(homeTeamId);
VisitorTeam = new Team(visitorTeamId);
}
// Reference Objects
public DateTime Date { get; set; }
public Park GamePark { get; set; }
public Team HomeTeam { get; set; }
public Team VisitorTeam { get; set; }
// Value Objects
public int HomeScore { get; set; }
public int VisitorScore { get; set; }
public string ParkId { get; set; }
public int Attendance { get; set; }
}
我不确定此类的目的是什么,但是根据您的其他情况,它肯定需要一个Id属性。
public class Team
{
public Team(string teamId)
{
TeamId = teamId;
TeamsLeague = new League();
}
public string TeamId { get; set; }
public League TeamsLeague { get; set; }
public string Name { get; set; }
}
只需调用构造函数并为Teams传递2个值即可:
public void Example()
{
Game game = new Game("Team1","Team2");
db.Games.Add(game);
...
}
我希望这个基本结构以正确的方式指导您。 现在,所有内容都应该可以访问并且可写。 您甚至可以扩展您的类构造函数以设置更多参数(例如分数)。
挑选一些教程或寻找可以教您如何编码的朋友。 您现在脑子里显然有很多对编程的误解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.