首页 > 解决方案 > 是否可以通过合并类来缩短呼叫线?

问题描述

我正在为数据编写视图类,我将在数据类中调用多个方法,所以我想通过删除数据类的名称来缩短调用线,并且只编写方法和字段,就像它们是视图类的一部分一样。

public class Data
{
  public int field1;
  public string field2;

  public void ClearData()
  {
    field1 = 0;
    field2 = "";
  }
}

public class Main
{
  public void Foo(){
    var data = DataLoader.LoadData(); // load data from somewhere else
    using (data) // this is not working in c#, I've written using because I want it to be working like this
    {
      Console.WriteLine(field1.ToString()); // Acces to data.field1 by writing only field1 because this codeline is inside using (data) zone
      Console.WriteLine(field2); // Acces to data.field2 by writing only field2 because this codeline is inside using (data) zone
      ClearData(); // Acces to data.ClearData method by writing only ClearData() because this codeline is inside using (data) zone
    }
}

是否可以在c#中编写类似的东西?(c# 7.3)

PS我知道这是很难理解的糟糕代码,但我想知道是否有可能这样做。

标签: c#unity3d

解决方案


不,你不能这样做

field1.ToString()

如果不指定它们所在的对象,编译器就无法知道“field1”、“field2”等是什么。

using (data)

不像在其他一些语言中那样工作,它说“将此对象用于所有字段引用”并且编译器从那里解决它。

你会写类似的东西

using (var data = DataLoader.LoadData())
{
  Console.WriteLine(data.field1.ToString()); 
  Console.WriteLine(data.field2); 
  ClearData(); **<<< nothing like this exists**
}

推荐阅读