崩溃控制台应用程序
这是我的问题:崩溃控制台应用程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public abstract class EntityMember<T>
{
public T Value { get; set; }
}
public class Int32EntityMember : EntityMember<int?>
{
}
public class StringEntityMember : EntityMember<string>
{
}
public class GuidEntityMember : EntityMember<Guid?>
{
}
public class Entity
{
public GuidEntityMember ApplicationId { get; private set; }
public Int32EntityMember ConnectedCount { get; private set; }
public GuidEntityMember MainApplicationId { get; private set; }
public Int32EntityMember ProcessId { get; private set; }
public StringEntityMember ProcessName { get; private set; }
}
class Program
{
static void Main(string[] args)
{
Entity entity2 = new Entity();
Guid empty = Guid.NewGuid();
Guid applicationId = Guid.NewGuid();
int Id = 10;
string name = "koko";
entity2.MainApplicationId.Value = new Guid?(empty);
entity2.ApplicationId.Value = new Guid?(applicationId);
entity2.ProcessId.Value = new int?(Id);
entity2.ProcessName.Value = name;
entity2.ConnectedCount.Value = 1;
}
}
}
的应用已完全阻断上线:
entity2.MainApplicationId. Value = new Guid? (empty);
为什么?
您收到的例外是:
Object reference not set to an instance of an object.
这是因为entity2.MainApplicationId
为空。你的Entity
类没有一个构造函数来设置MainApplicationId
不为null,因此你看到的错误。
添加一个构造函数来你Entity
类如下图所示运行结果在代码中没有错误代码:
public Entity()
{
ApplicationId = new GuidEntityMember();
ConnectedCount = new Int32EntityMember();
MainApplicationId = new GuidEntityMember();
ProcessId = new Int32EntityMember();
ProcessName = new StringEntityMember();
}
使用Auto-Implemented properties不会导致底层字段(即创建和管理您的名义编译器)在构建实例时为new
'd。因此,接下来的两个属性是不一样:
public MyClass MyProperty { get; private set; }
private MyClass _myOtherProperty = new MyClass();
public MyClass MyOtherProperty
{
get
{
return _myOtherProperty;
}
set
{
_myOtherProperty = value;
}
}
实际上'entity2'的所有字段为空 – ChrisF 2010-08-26 11:40:27
谢谢为答案。 (); 但是对于getter和setter我认为这两个是一样的, public MyClass myProperty(get; set;) private MyClass = new MyClass _myOtherProperty(); 公共MyClass的MyOtherProperty ( 得到 ( _myOtherProperty返回; ) 一起 ( _myOtherProperty =值; ) ) – Koka 2010-08-26 11:55:39
@Koka,两人显然是*不*一样的,因为我在已经解释回答,因为在第一个“自动属性”中,后台字段没有得到“MyClass”的新实例,而在第二个例子中,它确实。 – Rob 2010-08-26 12:04:07
尝试更改线路类型转换:
entity2.ApplicationId.Value = (Guid?)(applicationId);
什么错误(如果有的话),你看见了什么? – ChrisF 2010-08-26 11:37:12
Koka,欢迎来到* =)当你在这里提出问题时,尽可能多地显示相关信息总是很有用,所以你看到的任何异常的内容都是有用的,以及你的代码=)如果我们的答案之一解决了您的问题,请点击答案旁边的勾号大纲以将其标记为“已接受的答案”。确保你这样做会让人更倾向于回答你在这里问的任何未来问题=)(*编辑:我可以看到你刚刚完成了!*) – Rob 2010-08-26 11:47:31