简体   繁体   English

为什么投射对象是多余的

[英]Why casting the object is redundant

I have two constructors for an expandable list as shown below, and i have one interface shown below as well. 我有两个可扩展列表的构造函数,如下所示,我也有一个接口如下所示。 now i want to use the same expandlist adapter for two different activities that's why i created two constructors. 现在我想为两个不同的活动使用相同的expandlist适配器,这就是我创建两个构造函数的原因。 but the problem is when initialise the constructors, as you see in the 1st constructor when i initilaise the interface object to the 2nd parameter in the constructor, i receive "Redundant casting" while in the 2nd constructor it is mandatory to initialise the interface object to the 2nd parameter which the activity that should implement that interface 但问题是当初始化构造函数时,正如你在第一个构造函数中看到的那样,当我将接口对象初始化为构造函数中的第二个参数时,我会收到“Redundant casting”,而在第二个构造函数中,必须初始化接口对象应该实现该接口的活动的第二个参数

please explain why the casting in the 1st constructor is rundant while its manadory in the 2nd one? 请解释为什么第一个构造函数中的铸件是第二个,而第二个中的铸件是第二个?

update 更新

both activities extends AppCompatActivity

*code : *代码

public MyExpandableList(Context ctx, ActMain actMain, ArrayList<Group> groupList) {
    this.mCtx = ctx;
    this.mGroupList = groupList;
    this.mBTUtils = new BTUtils(ctx);
    this.mDevDetailsObserver =  (IDeviceDetailsPasser) actMain;//redundant casting, which is not necessary
}

public MyExpandableList(Context ctx, ActConnect actConnect, ArrayList<Group> groupList) {
    this.mCtx = ctx;
    this.mGroupList = groupList;
    this.mBTUtils = new BTUtils(ctx);
    this.mDevDetailsObserver = (IDeviceDetailsPasser) actConnect;//manadory casting

}

//interface
public interface IDeviceDetailsPasser {
public void onDevicedetailsChosen(Header header, Details details, int groupPos);

} }

似乎ActMain已经实现了IDeviceDetailsPasser ,这就是为什么冗余的转换。

I think in this case, your actMain implements IDeviceDetailsPasser , so casting is redundant, while your actConnect does not implement IDeviceDetailsPasser , so casting is mandatory. 我认为在这种情况下,您的actMain实现了IDeviceDetailsPasser ,因此转换是多余的,而您的actConnect不实现IDeviceDetailsPasser ,因此强制转换。

EDIT : to handle ClassCastException, use try/catch 编辑 :要处理ClassCastException,请使用try/catch

    try {
        mDevDetailsObserver = (IDeviceDetailsPasser) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement IDeviceDetailsPasser");
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM