我将以下代码编写为一个快速而肮脏的POC,一切正常,直到我尝试访问我创建的数组中的对象。
正如您在下面的代码中看到的,我尝试使用以下代码行访问数组中的对象:
Console.WriteLine("AWS Account Id = {0]", array1[1].AccountId);
整个代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
public class AWSAccount
{
public string AccountId { get; set; }
public string[] Instances { get; set; }
public AWSAccount(string accountId, string[] instances)
{
AccountId = accountId;
Instances = instances;
}
}
class Program
{
static void Main()
{
string[] instances1 = {"i-xxxxx01", "i-xxxxx02"};
AWSAccount account1 = new AWSAccount("53853288254", instances1);
Console.WriteLine("AWS Account Id = {0} Instances = {1} {2}", account1.AccountId, account1.Instances[0], account1.Instances[1]);
string[] instances2 = { "i-zzzzz01", "i-zzzzz02" };
AWSAccount account2 = new AWSAccount("74378834238", instances2);
Console.WriteLine("AWS Account Id = {0} Instances = {1} {2}", account2.AccountId, account2.Instances[0], account2.Instances[1]);
object[] array1 = new object[2];
array1[0] = account1;
array1[1] = account2;
Console.WriteLine("AWS Account Id = {0}", array1[0].AccountId);
Console.WriteLine("AWS Account Id = {0}", array1[1].AccountId);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
intellisense没有拾取.AccountId,它会突出显示以下错误。
Error 1 'object' does not contain a definition for 'AccountId' and no extension method 'AccountId' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?) c:\Users\jploof\Documents\Visual Studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs 37 65 ConsoleApplication1
答案 0 :(得分:1)
将您的对象[]更改为AWSAccount [],应该将您排除在外。
答案 1 :(得分:1)
使用AWSAccount[] array1 = new AWSAccount[2]
更正您的Main()程序,如下所示:
static void Main(string[] args)
{
string[] instances1 = { "i-xxxxx01", "i-xxxxx02" };
AWSAccount account1 = new AWSAccount("53853288254", instances1);
Console.WriteLine("AWS Account Id = {0} Instances = {1} {2}", account1.AccountId, account1.Instances[0], account1.Instances[1]);
string[] instances2 = { "i-zzzzz01", "i-zzzzz02" };
AWSAccount account2 = new AWSAccount("74378834238", instances2);
Console.WriteLine("AWS Account Id = {0} Instances = {1} {2}", account2.AccountId, account2.Instances[0], account2.Instances[1]);
AWSAccount[] array1 = new AWSAccount[2];
array1[0] = account1;
array1[1] = account2;
Console.WriteLine("AWS Account Id = {0}", array1[0].AccountId);
Console.WriteLine("AWS Account Id = {0}", array1[1].AccountId);
// Keep the console open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
注意原始帖子中的语法错误:"AWS Account Id = {0]"
希望这可能会有所帮助。