Skip to main content
 首页 » 编程设计

c#之通过方法而不是直接公开属性

2024年02月13日14落叶

我有一个非常简单的要求

public class A 
{ 
   public int Index{get;set;} 
 
   public B ConfigOne{get;set;} 
   public B ConfigTwo{get;set;} 
 
  public void SetConfigOne(string val1, string val2); 
  public void SetConfigTwo(string val1, string val2); 
} 
 
public class B 
{ 
   public string Val1{get;set;} 
   public string Val2{get;set;} 
} 

如何安排我的两个类(class),以便我能够做到这一点:

  var a = A.ConfigOne.Val1; 

但不是

A.ConfigOne.Val1 = a; 

所以基本上我想让我的间接类 (B) 属性只读,但仍然可以在类 A 中设置。 我想通过一种方法公开二传手。我怎么做?

请您参考如下方法:

创建一个接口(interface),该接口(interface)只公开一个B 可以实现的数据的只读 View 。这意味着任何直接引用 B 对象的人都可以设置它的数据,但是当从 A 中的属性访问时,它将是只读的:

public interface IReadValues 
{ 
    string Val1 { get; } 
    string Val2 { get; } 
} 
 
public class A 
{ 
    public int Index { get; set; } 
 
    public IReadValues ConfigOne { get; set; } 
    public IReadValues ConfigTwo { get; set; } 
 
    public void SetConfigOne(string val1, string val2); 
    public void SetConfigTwo(string val1, string val2); 
} 
 
public class B : IReadValues 
{ 
    public string Val1 { get; set; } 
    public string Val2 { get; set; } 
} 

通过不使用自动属性,而是让 A 具有通过显式属性公开的 B 类型的字段,您可以确保 A 类也可以修改这些对象。