c# - 是否可以通过合并类来缩短呼叫线?
问题描述
我正在为数据编写视图类,我将在数据类中调用多个方法,所以我想通过删除数据类的名称来缩短调用线,并且只编写方法和字段,就像它们是视图类的一部分一样。
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我知道这是很难理解的糟糕代码,但我想知道是否有可能这样做。
解决方案
不,你不能这样做
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**
}
推荐阅读
- encryption - 通过网络在两台设备之间共享公钥 [RSA]
- python - 在进程之间共享布尔值
- c# - 如何将数据库表与excel与c#中的相同列进行比较?
- php - Opencart 控制器数据未在视图中定义
- ios - UIImagePickerController 没有选择图像
- c++ - OpenCV 中的 findContours 与 Matlab 中的 bwboundaries 不匹配?
- ruby-on-rails - 如何获取活动存储视频附件的持续时间?
- security - 将多部分表单数据(POST)发送到多部分表单数据(GET)的任何方式
- batch-file - 如何拖放多个文件?
- c# - SignalR 服务器自主机