当谈到Java时,我仍然是一个相对的新手,主要来自C#背景。我应该使用匿名内部类来模拟Java中的'out'参数吗?
我讨论缺乏Java方法与同事,以及如何解决这个“出”参数。他建议创建一个结构/类来保存各种参数并将其传回。
有时,这种感觉“错误”我 - 特别是如果我有,我想用从一个更大的类返回的参数的子集的特殊方法。
所以我想知道如何使用匿名内联类来实现这一点。下面的代码示例。
这是一个明智的做法吗?只是想知道这种感知的智慧是什么。
public class MyClass {
Patient myPatient = null;
// An interface to enable us to return these variables in a single call
public interface VitalStatsResponse { public void returnStats(int bloodPressure, int heartRate); }
public class Patient {
int bloodPressure = 100;
int heartRate = 280;
// Lots of other variables here
public void calculateVitalStats(VitalStatsResponse response)
{
response.returnStats((bloodPressure * 2), (heartRate/10) ;
}
}
public void doWork()
{
// We want the patient's blood pressure and heart rate returned by a single method call, so use an anonymous inline class
myPatient.calculateVitalStats(new VitalStatsResponse() {
@Override
public void returnStats(int bloodPressure, int heartRate) {
// Handle returned variables here
}
});
}
}
就个人而言,我会在C#中使用“类来保存我关心的属性”,而不是使用'out'参数 - 如果某组属性具有有用的含义,为什么没有类型呢?通常我发现做到这一点,“更大的阶级”也可以使用它,并且变得更简单。例如,Person类不应该有“DateOfBirth,Street1,Street2,Street3,ZipCode,Country”......他们应该(可能)有“DateOfBirth,Address”。 out参数方法对于* private *方法有一定意义,但我不是公众的粉丝。 – 2015-03-19 12:05:43