2015-05-21 71 views
-3

我有一個類併爲它分配了一些屬性。從C#中的類中移除屬性

class MyClass 
{ 
     [Category("Common")] 
     [Description("Name")] 
     [Browsable(true)] 
     public string Name 
     { 
      get { return name;} 
      set { name = value; } 
     } 

     [Category("Common")] 
     [Description("Contact")] 
     [Browsable(true)] 
     public string ContactNo 
     { 
      get { return number;} 
      set { number = value; } 
     } 
} 

這裏, 當我實例化這個類,我想,當滿足特定條件,以除去contactNo財產。我怎樣才能做到這一點?

+0

你是什麼意思刪除屬性? – Mivaweb

+0

你不能「刪除」屬性...你想要做什麼? – xanatos

+0

@Mivaweb:我的意思是我不想在屬性網格中顯示該屬性。 – user4818954

回答

-1
class MyClass 
{ 
    [Category("Common")] 
    [Description("Name")] 
    [Browsable(true)] 
    public string Name 
    { 
     get { return name;} 
     set { name = value; } 
    } 

    [Category("Common")] 
    [Description("Contact")] 
    [Browsable(true)] 
    public string ContactNo 
    { 
     get { return number;} 
     set { number = value; } 
    } 

    public bool ContactNoVisible 
    { 
     //Change the condition 
     get {return Name != "bttb"; } 
    } 
} 

從現在開始只要檢查ContactNoVisible是否顯示網格屬性。如果你告訴我你的代碼如何顯示porperty值,那麼我也會以這種方式提供幫助。

0

你的方法取決於該屬性是否應該隱藏在表中的所有行(即如果你想隱藏整個列或只是在某些單元格中的值)。

如果您只想隱藏某些單元格中的值,則可以向屬性的集合部分添加條件以檢查條件並返回null或空字符串。如果條件需要檢查外部值,你可以有一個Get方法來接受合適的值來檢查。

在UI級別,要隱藏整個列,它實際上取決於您使用的技術。你在這裏沒有提到 - 對於基於瀏覽器的應用程序,JQuery可能是最常用的工具。

0

第一步將創建一個具有每個類將具有的屬性的抽象類。

例如:

public abstract class ClassRoot { 
    public string Name 
    { 
     get; set; 
    } 
} 

現在,您將創建派生類與其他屬性,可以彼此不同。

例如:

public class Class1 : ClassRoot { 
    public string ContactNo 
    { 
     get; set; 
    } 
} 

另一類可能是這樣的:

public class Class2 : ClassRoot { 
    public string Address 
    { 
     get; set; 
    } 
} 

現在根據你的病情,你可以這樣做:

if(....) 
{ 
    Class1 class1 = new Class1(); 
} else { 
    Class2 class2 = new Class2(); 
} 

每類Class1Class2有財產Name,但contai ns也是他們自己定義的屬性。