这是我的问题:
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);
为什么?
答案 0 :(得分:2)
您收到的例外是:
对象引用未设置为对象的实例。
这是因为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
。因此,后面的两个属性不相同:
public MyClass MyProperty { get; private set; }
private MyClass _myOtherProperty = new MyClass();
public MyClass MyOtherProperty
{
get
{
return _myOtherProperty;
}
set
{
_myOtherProperty = value;
}
}
答案 1 :(得分:0)
尝试将该行更改为类型转换:
entity2.ApplicationId.Value = (Guid?)(applicationId);