jeudi 26 décembre 2019

Reading attribute usage in property?

How do you read property based attributes at run time using Reflection in C#?


I have created a class similar to this:

public class PictureField
{
  public IList<Cropping> Croppings { get; set; }
}

public class Cropping
{
  public int Width { get; set; }
  public int Height { get; set; }
  public string Device { get; set; }
  public string SrcSet { get; set; }
}

I want to be able to dynamically control the list of Croppings on an instance of my PictureField class via attribution. I want the parent object to be able to control this. For example, I want to be able to do this:

public class ResponsiveHeroImage
{
  public string AltText { get; set; }

  [CropPoint(1920, 640, "Desktop", "(min-width: 1260px)")]
  [CropPoint(1259, 640, "Tablet", "(min-width: 960px) and (max-width: 1259px)")]
  [CropPoint(758, 384, "Mobile", "(max-width: 959px)")]
  public virtual PictureField ResponsiveImage { get; set; }
}

public class ResponsiveBlockImage
{
  public string AltText { get; set; }

  [CropPoint(1024, 540, "Desktop", "(min-width: 960px)")]
  [CropPoint(758, 384, "Mobile", "(max-width: 959px)")]
  public virtual PictureField ResponsiveImage { get; set; }
}

so I have created an attribute like so:

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
public class CropPointAttribute : Attribute
{
  public CropPointAttribute(int width, int height, string device, string srcSet)
  {
    this.Width = width;
    this.Height = height;
    this.Device = device;
    this.SrcSet = srcSet;
  }

  public int Width { get; }
  public int Height { get; }
  public string Device { get; }
  public string SrcSet { get; }
}

However, I cannot figure out how to read the CropPoint attribute from within my PictureField class. How can I get a handle on the parent object and read the attributes they have declared?





Aucun commentaire:

Enregistrer un commentaire