读取属性中的属性用法?



如何在运行时使用 C# 中的反射读取基于属性的属性?


我创建了一个类似于这样的类:

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; }
}

我希望能够通过归因动态控制 PictureField 类实例上的裁剪列表。 我希望父对象能够控制这一点。 例如,我希望能够做到这一点:

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; }
}

所以我创建了一个这样的属性:

[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; }
}

但是,我不知道如何从我的PictureField类中读取CropPoint属性。 如何获取父对象的句柄并读取它们声明的属性?

我认为无论如何都无法从PictureField访问属性。但是,您可以从ResponsiveBlockImage访问该属性,并使用其属性ResponsiveBlockImage。可以直接从代码传递值,而不是通过分配属性来传递值。为什么要使用属性?

最新更新