简体   繁体   中英

How to make a field set-able only inside extension method

Hello i want to be able to set the a of a field of an object only in an extension method. I would want that this field to either be completelely private , or be just get -able from outside:

public class Myclass
{
   private int Value{get;set;}
}
public static class Ext
{
   public Myclass SetValue(this Myclass obj,int val)
   {
       this.obj.Value=val;
       return obj;
   }
}

As you can see in the above example , i have to declare Value public to be able to access it inside the extension , i would be ok with that if i could make the variable only get-able from outside.

I need this functionality because i want to develop something like a fluent api , where you can only set some variables using the extension.

ex:

      a=new Myclass();
      a.SetValue1(1).SetValue2(2);//--some code //--a.SetValue3(3);

It sounds like you're using the wrong tool for the job, extension methods don't have access non-public members.

The behavior you want is restricted to instance methods or properties. My recommendation is to add an instance method to the class.

If that doesn't persuade you, then you can instead use reflection to update the private instance variable:

public static class Ext
{
    public Myclass SetValue(this Myclass obj,int val)
    {
        var myType = typeof(Myclass);

        var myField = myType.GetField("Value", BindingFlags.NonPublic | BindingFlags.Instance);

        myField.SetValue(obj, val);

        return obj;
   }
}

Please note that this has the following gotchas:

  1. There are no compile time checks to save you if you decide to rename the field Value . (though unit tests can protect you)
  2. Reflection is typically much slower than regular instance methods. (though performance may not matter if this method isn't called frequently)

you want it to do it with extension method but you cannot in this case.

Your best option is

public class Myclass
{
   public int Value{get; private set;}

   public Myclass SetValue(int val)
   {
       this.Value=val;

       return obj;
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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