Setting a ref to a member field in C#

前端 未结 6 1898
悲哀的现实
悲哀的现实 2021-02-08 13:32

I\'d like to assign a reference to a member field. But I obviously do not understand this part of C# very well, because I failed :-) So, here\'s my code:

public          


        
6条回答
  •  情书的邮戳
    2021-02-08 14:05

    If you don't want to introduce another class like MyRef or StringBuilder because your string is already a property in an existing class you can use a Func and Action to achieve the result you are looking for.

    public class End {
        private readonly Func getter;
        private readonly Action setter;
    
        public End(Func getter, Action setter) {
            this.getter = getter;
            this.setter = setter;
            this.Init();
            Console.WriteLine("Inside: {0}", getter());
        }
    
        public void Init() {
            setter("success");
        }
    }
    
    class MainClass 
    {
        public static void Main(string[] args) 
        {
            string s = "failed";
            End e = new End(() => s, (x) => {s = x; });
            Console.WriteLine("After: {0}", s);
        }
    }
    

    And if you want to simplify the calling side further (at the expense of some run-time) you can use a method like the one below to turn (some) getters into setters.

        /// 
        /// Convert a lambda expression for a getter into a setter
        /// 
        public static Action GetSetter(Expression> expression)
        {
            var memberExpression = (MemberExpression)expression.Body;
            var property = (PropertyInfo)memberExpression.Member;
            var setMethod = property.GetSetMethod();
    
            var parameterT = Expression.Parameter(typeof(T), "x");
            var parameterU = Expression.Parameter(typeof(U), "y");
    
            var newExpression =
                Expression.Lambda>(
                    Expression.Call(parameterT, setMethod, parameterU),
                    parameterT,
                    parameterU
                );
    
            return newExpression.Compile();
        }
    

提交回复
热议问题