C# reference member variable

前端 未结 5 611
情深已故
情深已故 2021-01-17 23:26

In C#, is there a way to keep a reference as a member variable in an object (like an object pointer in C++), not just as a parameter?

EDIT: How can I make a p

5条回答
  •  清歌不尽
    2021-01-17 23:58

    For what its worth, you could use an array of size 1 as a reference/pointer. This yields more readable code than creating a new class to wrap a single value type member.

    public struct StructWithReferenceMember
    {
        private int[] intStoredAsReference;
    
        public StructWithReferenceMember(int asValue, int asReference)
            : this()
        {
            IntStoredAsValue = asValue;
            intStoredAsReference = new int[] { asReference };
        }
    
        public int IntStoredAsValue { get; set; }
        public int IntStoredAsReference
        {
            get { return intStoredAsReference[0]; }
            set { intStoredAsReference[0] = value; }
        }
    }
    

    A similar trick can be used to attempt the highly discouraged practice of using mutable structs.

    public class ReferenceProperty
    {
        private T[] typeReference;
    
        public ReferenceProperty(T value)
        {
            typeReference = new T[] { value };
        }
    
        public T PropertyAsValue
        {
            get { return typeReference[0]; }
            set { typeReference[0] = value; }
        }
        public T[] PropertyAsReference
        {
            get { return typeReference; }
        }
    }
    

    Then use array notation to "dereference" it.

    public struct MutableStruct
    {
        public int member;
    
        public MutableStruct(int value)
        {
            member = value;
        }
    }
            ReferenceProperty referenceToValueType = new ReferenceProperty(new MutableStruct(3));
            Console.WriteLine("original value: " + referenceToValueType.PropertyAsValue.member.ToString());
    
            //referenceToValueType.PropertyAsValue.member = 4; // compiler error - cannot modify return value because it is not a variable
            MutableStruct copyOfStruct = referenceToValueType.PropertyAsReference[0]; // or referenceToValueType.PropertyAsValue
            copyOfStruct.member = 4;
            Console.WriteLine("original value after modifying copy: " + referenceToValueType.PropertyAsValue.member.ToString());
    
            referenceToValueType.PropertyAsReference[0].member = 5;
            Console.WriteLine("original value after modifying reference: " + referenceToValueType.PropertyAsValue.member.ToString());
    

    original value: 3
    original value after modifying copy: 3
    original value after modifying reference: 5
    

提交回复
热议问题