簡體   English   中英

如何在構造函數執行期間在異常處理程序中分配類實例

[英]How to assign class instances in exception handler during constructor execution

    public Alphabet(params char[] list)
    {
        this.ExceptionInitializer();
        try
        {
            if (list != null) _alphabet = list;
            else throw this.NullableAssignment; //add exception handler;
            this._charCounter = list.Length;
        }
        catch (this.NullableAssignment)
        {
          //  var x = new Alphabet();   
          //  this = x;      //FAIL!
        }
    }

您提出的代碼在C#中無效,您不能為this分配任何值。 您可以做的是使用對默認構造函數的調用,如下所示:

public Alphabet() { /* Do some default initialization here */ }

public Alphabet(params char[] list) : this() // The call to the default constructor.
{ 
    if (list != null) 
    {
        _alphabet = list; 
        this._charCounter = list.Length; 
    }
} 

我不知道你想做什么。 您可以顯示ExceptionInitializer和NullableAssignment嗎? 當沒有參數傳入時,是否要為_alphabet分配一個空數組?

public Alphabet(params char[] list)
{
    if(list != null)
    {
        _alphabet = list;
    }
    else
    {
        _alphabet = new char[0];
    }
    this._charCounter = _alphabet.Length;
}

這將適用於任意數量的參數或顯式null:

new Alphabet('f', 'o', 'o')
new Alphabet()
new Alphabet(null)

我猜想您希望Alphabet的構造函數處理list的元素,除非list為空,在這種情況下,應使用特殊的“空對象”。 不幸的是,這不能使用普通的構造函數來完成。 您需要的是工廠方法:

private static Alphabet _emptyAlphabet = new Alphabet();
private Alphabet(char[] list) { /* etc */ }

public Alphabet CreateAlphabet(params char[] list)
{
    if (list == null)
    {
        return _emptyAlphabet;
    }
    else
    {
        return new Alphabet(list);
    }
}

您無法執行此操作-最接近的事情是創建一個靜態工廠方法,該方法返回一個Alphabet

public class Alphabet
{
    private Alphabet(params char[] list)
    {
         //setup
    }

    public static Alphabet Create(params char[] list)
    {
        return list == null
            ? new Alphabet()
            : new Alphabet(list);
    }
}

盡管給出了示例,但更簡單的方法是在null處分配一個空數組:

public Alphabet(params char[] list)
{
    _alphabet = list ?? new char[] { };
    this._charCounter = _alphabet.Length;
}
public Alphabet() {
    ConstructEmptyAlphabet();
}

public Alphabet(char[] list) {
    if (list == null) {
        ConstructEmptyAlphabet();
    } else {
        _alphabet = list;
        this._charCounter = list.Length;
    }
}

private void ConstructEmptyAlphabet() {
    …
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM