[英]Reading attribute usage in property?
如何在運行時使用 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
及其屬性訪問該屬性。 您可以直接從代碼中傳遞值,而不是通過分配屬性來傳遞值。 你為什么要使用屬性?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.