An object with a custom visibility property

I have a User object with many properties. I have a requirement that indicates when the user sets their information, they need the ability to specify which properties of their profile are visible to others.

The way I assumed it was to add an additional property - a list of strings that would contain the names of the properties that were publicly available. Then I could implement a method called ToPublicView () or something similar that would use reflection to set non-public properties to null or default.

Is this a smart approach or is there a better way?

+5
source share
4 answers

, . , - .

, , , (, ). , , .

+1

, , , :

public Class Property<T>
{
    public Property(string name, bool visible, T value)
    {
        Name = name;
        Visible = visible;
        Value = value;
    }

    string Name { get; set; }
    bool Visible { get; set; }
    T Value { get; set; }
}

, :

List<Property> properties = new List<Property>();
properties.Add(new Property<string>("FirstName", true, "Steve"));

, -, . ? /? ? .. , .

+1

What? No. If this is a requirement, then User properties should not be implemented using real properties, but instead some IEnumerable and Property objects are used, where each property has visibility, etc.

0
source

Maybe some combination of custom DynamicObject implementations may be used .

EDIT

  //custom property class
  public class MyProperty
  {
      public bool IsVisible { get; set; }
      public string PropertyName { get; set; }
  }

  public class Dymo: DynamicObject
  {

      Dictionary<MyProperty, object> dictionary
          = new Dictionary<MyProperty, object>();

      public override bool TryGetMember(
          GetMemberBinder binder, out object result)
      {
          result = false;
          var prop = PropertyFromName(binder.Name);
          if (prop != null && prop.IsVisible)
              return dictionary.TryGetValue(prop, out result);

          return false;

      }

      public override bool TrySetMember(
          SetMemberBinder binder, object value)
      {

          var prop = PropertyFromName(binder.Name);
          if (prop != null && prop.IsVisible)
              dictionary[prop] = value;
          else
              dictionary[new MyProperty { IsVisible = true, PropertyName = binder.Name}] = value;
          return true;
      }

      private MyProperty PropertyFromName(string name)
      {
          return (from key in dictionary.Keys where key.PropertyName.Equals(name) select key).SingleOrDefault<MyProperty>();
      }


      public void SetPropertyVisibility(string propertyName, bool visibility)
      {
          var prop = PropertyFromName(propertyName);
          if (prop != null)
              prop.IsVisible = visibility;         
      }
  }

and use it, after that.

dynamic dynObj = new Dymo();
dynObj.Cartoon= "Mickey" ;
dynObj.SetPropertyVisibility("Mickey", false); //MAKE A PROPERTY "INVISIBLE"
0
source

All Articles