如何在构造函数执行期间在异常处理程序中分配类实例

时间:2010-05-19 22:39:25

标签: c# .net

    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!
        }
    }

5 个答案:

答案 0 :(得分:2)

您建议的代码在C#中无效,您无法为分配任何值。你可以做的是使用这样的默认构造函数调用:

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

答案 1 :(得分:0)

我不知道你要做什么。你能展示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)

答案 2 :(得分:0)

我猜你希望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);
    }
}

答案 3 :(得分:0)

你不能这样做 - 最接近的是创建一个返回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;
}

答案 4 :(得分:0)

public Alphabet() {
    ConstructEmptyAlphabet();
}

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

private void ConstructEmptyAlphabet() {
    …
}