将对象作为out参数传递

Ale*_*xey 5 c# reference

我有一个方法,检查对象的有效性与我的程序(某些算法).从传入的字符串创建(解析)对象.

逻辑是:

 bool isValid(String str, out Object obj)
    {
         obj = null;
         obj = new Object(str); //Validation happens during the object creating
         if(obj.Legit) //Don't mind this line :)
             return true;
         return false;
    }
Run Code Online (Sandbox Code Playgroud)

我从另一个类调用此验证,如果此验证失败,则执行不同的验证(相同方法)

void FindingObjectType(String str)
{
        if(isValid(str, out ??????)
             //process
}
Run Code Online (Sandbox Code Playgroud)

所以不是?????,我不知道如何传递对象.

我只有1个构造函数,Object(String).

nic*_*nic 8

此MSDN文档描述了"out"关键字:
http://msdn.microsoft.com/en-us/library/t3c3bfhx

(v = vs.80).aspx在调用isValid()方法之前,需要声明输出对象:

void FindingObjectType(String str)
{
    Object obj;
    if(isValid(str, out obj)
         //process
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*ert 7

正如尼克所说,通常你会说:

void FindingObjectType(String str)
{
    object obj;
    if(isValid(str, out obj)
    {
         // process valid obj
    }
}
Run Code Online (Sandbox Code Playgroud)

那是完全可以接受的.但是,还有其他方法可以做到这一点,可能更好:

Thing GetThing(String str)
{
     Thing thing = new Thing(str);
     if(thing.Legit)
         return thing;
     return null;
}

void FindingObjectType(String str)
{
    Thing thing = GetThing();
    if(thing != null)
         //process
}
Run Code Online (Sandbox Code Playgroud)

这是另一个:

Thing GetThing(String str)
{
     // Make a static method that tests the string.
     if (Thing.IsLegit(str)) 
         return new Thing(str);
     return null;
}

void FindingObjectType(String str)
{
    Thing thing = GetThing();
    if(thing != null)
         //process
}
Run Code Online (Sandbox Code Playgroud)

当然,如果你要这样做那么为什么你需要GetThing?说啊:

void FindingObjectType(String str)
{
     if (Thing.IsLegit(str)) 
     {
         Thing thing = new Thing(str);
         //process
     }
}
Run Code Online (Sandbox Code Playgroud)

最后一种模式可能是最好的.你想分开你的顾虑.当你有一个out参数时,通常是因为该方法试图做太多事情.

  • @TimLehner:我非常希望`int.TryParse`返回一个`int?`而不是bool和out参数. (6认同)