2014-03-25 36 views
0

反正要提出的是,這樣我可以這樣說使用類作爲布爾值時的自定義函數?

if(boolClass) {} 

凡boolClass被調用包含的功能。有點像超載的布爾操作符或其他東西。

感謝您的任何幫助。

+1

我不跟着你。你能解釋一下你爲什麼要這樣做嗎? – Amicable

+1

呃...什麼?你需要改進這個解釋。你能提供一個你期望能夠做的例子嗎? – Kjartan

+1

[隱式轉換](http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx)? –

回答

2

其實是有一個「真正的」操作符,你可以使用這個目的,雖然這是一個有點朦朧。這比轉換爲bool更具體,因爲它僅限於在檢查true/false的表達式中使用。

public class BoolClass 
{ 
    public static bool operator true(BoolClass instance) 
    { 
     return true; //Logic goes here 
    } 

    public static bool operator false(BoolClass instance) 
    { 
     return true; //Logic goes here 
    } 

    public void Test() 
    { 
     BoolClass boolClass = new BoolClass(); 
     if (boolClass) 
     { 
      //Do something here 
     } 
    } 
} 

注意,MS實際上recommends against using this operator,因爲它最初是爲了允許一種可空bool類型(其中一個值可以是不真不假的)的。由於可空的布爾現在被本機支持,所以這些是優選的。我建議不要在生產代碼中使用它,主要是因爲大多數開發人員不會熟悉語法,導致混淆。

0

添加conversion operator到您的班級。示例(ideone):

using System; 

public class A 
{ 
    private int i; 
    public int I { get { return i; } } 
    public A(int i) { this.i = i; } 
    public static implicit operator bool(A a) { return a.i != 0; } 
} 

public class Test 
{ 
    public static void Main() 
    { 
     A a1 = new A(0); 
     if (a1) 
      Console.WriteLine("a1 is true"); 
     else 
      Console.WriteLine("a1 is false"); 

     A a2 = new A(42); 
     if (a2) 
      Console.WriteLine("a2 is true"); 
     else 
      Console.WriteLine("a2 is false"); 
    } 
} 

輸出:

a1 is false 
a2 is true 
0

聽起來像一個屬性:

public bool boolClass 
{ 
    get { return false; } // or a calculated boolean value 
} 

你可以調用它就像你從同一個類中問:

if(boolClass) {} 
2

我的第一點是要提醒你不要這樣做,通常你想直接或間接使用boolbool?類。

如果您確定這是你所需要的,那麼你需要的隱式轉換操作符bool

//In the definition of boolClass 
public static implicit operator bool(boolClass obj) 
{ 
    //Return a bool in this method 
} 
1

您可以使用implicit operator將您的類轉換爲布爾值。

這是一個完整而簡單的例子:

CLASSE

using System; 

namespace TestLogic 
{ 
    internal class FuzzyLogic 
    { 
     public FuzzyLogic(Double init) 
     { 
      this.value = init; 
     } 

     public Double value { get; private set; } 

     public static implicit operator Boolean(FuzzyLogic logic) 
     { 
      return logic.value < 0.1; 
     } 
    } 
} 

使用皈依

using System; 

namespace TestLogic 
{ 
    internal class Program 
    { 
     private static void Main(string[] args) 
     { 
      FuzzyLogic logic = new FuzzyLogic(0.2); 

      if (logic) 
      { 
       Console.WriteLine("It's true !"); 
      } 
      else 
      { 
       Console.WriteLine("It's not true !"); 
      } 

      Console.ReadLine(); 
     } 
    } 
} 
相關問題