将接口作为参数传递

Pass Interface as Parameter

我阅读了下面的 altbeacon 示例,它写成 Java (http://altbeacon.github.io/android-beacon-library/samples.html)。我必须将代码翻译成 c#..

    @Override
public void onBeaconServiceConnect() {
    beaconManager.setMonitorNotifier(new MonitorNotifier() {
    @Override
    public void didEnterRegion(Region region) {
        Log.i(TAG, "I just saw an beacon for the first time!");        
    }

    @Override
    public void didExitRegion(Region region) {
        Log.i(TAG, "I no longer see an beacon");
    }

    @Override
        public void didDetermineStateForRegion(int state, Region region) {
        Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);        
        }
    });

    try {
        beaconManager.startMonitoringBeaconsInRegion(new Region("myMonitoringUniqueId", null, null, null));
    } catch (RemoteException e) {    }
}

我是这样开始的,现在我在传递接口参数时遇到了问题,就像在提到的例子中一样..

        public void OnBeaconServiceConnect()
    {
        beaconManager.SetMonitorNotifier(...)
     }

有人可以解释一下如何将代码转换为 C# 吗?

匿名 class 无法在 C# 中实现接口。 所以不要在这里使用匿名 class :

    public class MyMonitorNotifier : MonitorNotifier {
...
}

然后:

 beaconManager.SetMonitorNotifier(new MyMonitorNotifier ());

我认为你真正的问题是 "is there an equivalent to anonymous classes in C#?"。答案是否定的。

看看Java: Interface with new keyword how is that possible?。 Java 支持定义在方法中实现接口的匿名 classes。定义实现接口的私有 class 只是语法糖(或盐,取决于个人对此功能的看法)。

因此将此代码转换为 C# 时的解决方案是创建一个私有内部 class 并在方法中使用它:

class SomeClass
{
    ...
    public void OnBeaconServiceConnect() 
    {
        beaconManager.SetMonitorNotifier(new MonitorNotifier());
        ...
    }

    ...

    private MonitorNotifier : IMonitorNotifier
    {
        public void didEnterRegion(Region region) 
        {
            Log.i(TAG, "I just saw an beacon for the first time!");       
        }

        public void didExitRegion(Region region) 
        {
            Log.i(TAG, "I no longer see an beacon");
        }

        public void didDetermineStateForRegion(int state, Region region) 
        {
            Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);        
        }
    }
}