崩溃控制台应用

时间:2010-08-26 11:30:24

标签: c# console-application

这是我的问题:

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); 

为什么?

2 个答案:

答案 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);