Can we interrupt creating an object in constructor

前端 未结 7 1435
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-31 03:46

Could you help me please. I have one idea but don\'t know how can I implement it.

So the question is: Can we interrupt creating an object in constructor i.e.

相关标签:
7条回答
  • 2020-12-31 04:14

    If the parameters to your constructor are invalid, consider throwing ArgumentException or one of its descendant classes (e.g. ArgumentOutOfRangeException).

    0 讨论(0)
  • 2020-12-31 04:23

    You may want to use a factory class that creates instances of SomeClass returning null if the someCriteria is invalid.

    0 讨论(0)
  • 2020-12-31 04:25

    No it is not possible directly.

    You could throw an exception and add the required code to check for the exception and assign null to you variable.

    A better solution would be to use a Factory that would return null if some condition fail.

    var someClass = SomeClassFactory.Create(someCriteria);
    if(someClass != null)
    {
    }
    
    0 讨论(0)
  • 2020-12-31 04:26

    The new construct guarantees that an object will be returned (or an exception thrown). So as bleeeah recommended, a factory or similar concept will allow you to apply your logic.

    0 讨论(0)
  • 2020-12-31 04:30

    Best way is a factory class but if your class is so small you can use this:

    class SomeClass
        {
            private string _someCriteria;
    
            private SomeClass(string someCriteria)
            {
                _someCriteria = someCriteria;
            }
    
            public static SomeClass CreateInstance(string someCriteria)
            {
                if (someCriteria.Length > 2)
                {
                    return new SomeClass(someCriteria);
                }
                return null;
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
    
                // returns null
                SomeClass someClass = SomeClass.CreateInstance("t");
    
                // returns object
                SomeClass someClass2 = SomeClass.CreateInstance("test");
            }
        }
    
    0 讨论(0)
  • 2020-12-31 04:30

    That would be possible. Another way would be to put your checking in before you create the object. Like so

    SomeClass someClass = null;
    
    if (someCriteria == VALID)
    {
        someClass = new SomeClass(someCriteria);
    }
    

    Hope this helps.

    0 讨论(0)
提交回复
热议问题