我来自PHP和Javascript的Wild Wild West,您可以从函数返回任何内容.虽然我不喜欢缺乏问责制,但我在努力保持代码"完美"方面也遇到了新的挑战.
我制作了这个通用函数来从列表中选择一个随机元素
public static T PickRandom<T>(this IList<T> list) {
Random random = new Random();
int rnd = random.Next(list.Count);
return list[rnd];
}
Run Code Online (Sandbox Code Playgroud)
但我想保护自己不要在0值列表中使用它.显然我不能从T以外的函数返回任何东西,例如false或-1.我当然可以这样做
if(myList.Count > 0)
foo = Utilites.PickRandom(myList);
Run Code Online (Sandbox Code Playgroud)
然而,在C#中有很多疯狂的事情我不知道,对于这个应用程序,我正在创建我非常,经常必须从列表中选择一个可以在其Count中不断递减的随机元素.有没有更好的办法?
我正在使用Microsoft提供的Async示例编写我的第一个TCP服务器.
https://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx
我从示例中得到了一切.我将它扩展为一个简单的聊天程序.但是我无法遵循这个程序的步骤(可能是因为它的异步性质).收到消息后,它会回送给客户端并关闭套接字.我没有看到它重新打开插座的位置.
public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and listen for incoming connections. …Run Code Online (Sandbox Code Playgroud) 我有一个叫做的课BonusCell.它继承了这个GameEntity类.
public class BonusCell : GameEntity
{
public void GiveStats()
{
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个叫做的课 Cell
public Cell
{
public GameEntity gameEntity;
}
Run Code Online (Sandbox Code Playgroud)
我有一个游戏网格,其中包含2维数组Cell.
public class Board
{
public Cell[,] grid;
}
Run Code Online (Sandbox Code Playgroud)
BonusCell即使我使用if is声明来验证它是BonusCell什么,为什么我必须施放?我明白这board.grid[x,y].gameEntity是一种类型GameEntity,但如果这是真的,它is BonusCell怎么也可以是真的呢?
if (board.grid[x, y].gameEntity is BonusCell)
{
BonusCell bonusCell = (BonusCell)board.grid[x, y].gameEntity;
bonusCell.GiveStats();
}
Run Code Online (Sandbox Code Playgroud)