Replace object instance with another in C#

后端 未结 4 1051
长情又很酷
长情又很酷 2021-02-13 05:17

In this question I would like to find out if and how this is possible. This technique would seem extremely bad practice but it seems that the API (UnityEditor) that I am using,

4条回答
  •  野的像风
    2021-02-13 05:57

    If it is a custom Class you want to reference, i think you can have all the references point to a Fake Reference...

    1. create your class (A)
    2. create your class Interface (IA)
    3. Create a wrapper class based on your interface which just passes all calls to a contained object (AC)

    I Added a Assignment operator so i have all A Objects as ACs.

    class AC:IA  
    {  
        IA ref;  
        AC(IA ref)  
        {  
            this.ref = ref;  
        }  
    
        public void ChangeReference(IA newRef) { ref = newRef;}  
        public static operator = (IA assignedObj)  
        {  
            return (assignedObject is AC) ? assignedObject : new AC(assignedObj);
        }
    
        // implementation of all methods in A
        public override string ToString() { return ref.ToString(); }  
            ...  
    }
    

    Now if you want, you can use the ChangeReference method to switch all to the new Reference..

    in C++ you would use Reference to Reference

    Best of luck

提交回复
热议问题