2010-08-26 118 views
1

這是我的問題:崩潰控制檯應用程序

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

爲什麼?

+1

什麼錯誤(如果有的話),你看見了什麼? – ChrisF 2010-08-26 11:37:12

+0

Koka,歡迎來到stackoverflow =)當你在這裏提出問題時,儘可能多地顯示相關信息總是很有用,所以你看到的任何異常的內容都是有用的,以及你的代碼=)如果我們的答案之一解決了您的問題,請點擊答案旁邊的勾號大綱以將其標記爲「已接受的答案」。確保你這樣做會讓人更傾向於回答你在這裏問的任何未來問題=)(*編輯:我可以看到你剛剛完成了!*) – Rob 2010-08-26 11:47:31

回答

2

您收到的例外是:

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; 
    } 
} 
+2

實際上'entity2'的所有字段爲空 – ChrisF 2010-08-26 11:40:27

+0

謝謝爲答案。 (); 但是對於getter和setter我認爲這兩個是一樣的, public MyClass myProperty(get; set;) private MyClass = new MyClass _myOtherProperty(); 公共MyClass的MyOtherProperty ( 得到 ( _myOtherProperty返回; ) 一起 ( _myOtherProperty =值; ) ) – Koka 2010-08-26 11:55:39

+0

@Koka,兩人顯然是*不*一樣的,因爲我在已經解釋回答,因爲在第一個「自動屬性」中,後臺字段沒有得到「MyClass」的新實例,而在第二個例子中,它確實。 – Rob 2010-08-26 12:04:07

0

嘗試更改線路類型轉換:

entity2.ApplicationId.Value = (Guid?)(applicationId); 
相關問題