[英]Exclude Single or multiple property in a C# Class
在這里,我有“測試”課程。
public class test
{
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
void call1(test obj )
{
// Question: I need to exclude the property a. which means "test.a" should not able to access or view.
}
void call2(test obj )
{
// I need to exclude the property both a & b
return;
}
您可以在此處使用接口 :
public interface IRestrictedNoAandB {
int c { get; set; }
int d { get; set; }
}
public interface IRestrictedNoA: IRestrictedNoAandB {
int b { get; set; }
}
public class test: IRestrictedNoA {
public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
// You can't access property "a" within "call1" method
void call1(IRestrictedNoA obj ) {...}
// You can't access properties "a" and "b" within "call2" method
void call2(IRestrictedNoAandB obj ) {...}
您不能在OOP中執行此操作。 財產一旦公開,每個人都可以使用。 相反,您可以做的是創建像
public class test1
{
//public int a { get; set; }
public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
public class test2
{
//public int a { get; set; }
//public int b { get; set; }
public int c { get; set; }
public int d { get; set; }
}
並在上述兩種方法中使用它們。 然后使用諸如Glue
或ObjectMapper
類的對象映射器自動從test映射到test1和test2
但是使用此方法可能必須稍微更改程序的結構,如果返回test1和test2而不是void,然后更改主測試實例的值,則它將是awsm。
您可以嘗試兩種方法,然后嘗試new,您將返回一個匿名對象,該對象是測試的“部分”視圖。
public class test
{
private int a { get; set; }
private int b { get; set; }
private int c { get; set; }
private int d { get; set; }
public object testWithoutA()
{
var test = new
{
this.b,
this.c,
this.d
};
return test;
}
public object testWithoutAAndB()
{
var test = new
{
this.c,
this.d
};
return test;
}
}
更新:問題涉及從WCF REST PUT傳入的數據
假設您正在使用存儲過程,為什么不創建兩個在一種情況下忽略“ a”,“ a”和“ b”的存儲過程?
您不能在運行時更改對象的結構。
但是有很多方法可以防止訪問實例的屬性,例如,請參見以下代碼:
public class Test
{
// define some private varibales:
private int _a;
private int _b;
private bool accessA = true;
private bool accessB = true;
public int a
{
get
{
if (accessA)
{
return _a;
}
else
{
throw new Exception("At this moment this property was excluded.");
}
}
set
{
if (accessA)
{
_a = value;
}
else
{
throw new Exception("At this moment this property was excluded.");
}
}
}
public int b
{
get
{
if (accessB)
{
return _b;
}
else
{
throw new Exception("At this moment this property was excluded.");
}
}
set
{
if (accessB)
{
_b = value;
}
else
{
throw new Exception("At this moment this property was excluded.");
}
}
}
public int c { get; set; }
public int d { get; set; }
public void ExcludeA()
{
accessA = false;
}
public void ExcludeB()
{
accessB = false;
}
}
public void call1(Test obj)
{
//do some work here ....
obj.ExcludeA();
}
public void call2(Test obj)
{
// do some work here ...
obj.ExcludeA();
obj.ExcludeB();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.