我正在开发一个控制台应用程序,该应用程序也引用了类库。在类库中,我有以下代码。
namespace SomeClass
{
public class ClassOne
{
public string[] SupportedFiles;
}
}
在控制台应用程序,程序.cs中,我正在尝试分配支持的文件。
class Program
{
public ClassOne class1 { get; set; }
public Program()
{
class1.SupportedFiles = new string[] { "Test", "Test" };
//class1.SupportedFiles[0] = "First";
//class1.SupportedFiles[1] = "Second";
}
}
但是class1.SupportedFiles = new string[] { "Test", "Test" };
抛出的线
System.NullReferenceException: 'Object reference 未设置为 对象的实例。
我错过了什么?我这么笨吗,实例化一个字符串数组。请帮帮我。
您缺少存在string[]
的类实例
在访问string[]
之前尝试使用它
ClassOne cOne = new ClassOne();
不要错过将类库的引用添加到要访问此字符串的项目program.cs
并在文件中包含命名空间
这可以是您的工作解决方案:
using SomeClass;
class Program
{
//Not required to create property of ClassOne
//public ClassOne class1 { get; set; }
public Program()
{
//In this way, you can create instance of class.
ClassOne class1 = new ClassOne();
//Now with the help of instance of class, you can access all public properties of that class
class1.SupportedFiles= new string[] { "Test", "Test" };
//class1.SupportedFiles[0] = "First";
//class1.SupportedFiles[1] = "Second";
}
}
在访问对象成员之前,必须初始化对象。为此,您有几个(基本(选项:
class Program
{
public ClassOne Class1 { get; set; }
public Program()
{
Class1 = new ClassOne();
Class1.SupportedFiles= new string[] { "Test", "Test" };
}
}
甚至更好:
class Program
{
public ClassOne Class1 { get; set; }
public Program()
{
Class1 = new ClassOne()
{
SupportedFiles = new string[] { "Test", "Test" }
};
//class1.SupportedFiles[0] = "First";
//class1.SupportedFiles[1] = "Second";
}
}
或者,如果您使用的是C#6
及更高版本,则具有自动属性初始值设定项之类的东西:
class Program
{
public ClassOne Class1 { get; set; } = new ClassOne();
public Program()
{
Class1.SupportedFiles= new string[] { "Test", "Test" };
//class1.SupportedFiles[0] = "First";
//class1.SupportedFiles[1] = "Second";
}
}