Home >Backend Development >C++ >How to Add Validation Attributes to Runtime Properties in C#?
In your attempt to add a validation attribute to a property at runtime, you've encountered an exception stating "Collection was of a fixed size." To resolve this issue, consider the following:
The code you've provided involves invoking the FillAttributes method. This particular method, however, expects an array of attributes as its argument, not a single attribute. To rectify this, you should modify your code to pass an array containing the desired attribute:
// Create an array of attributes var attributes = new ValidationAttribute[] { attribute }; // Invoke FillAttribute method methodInfo.Invoke(propDesc, new object[] { attributes });
Alternatively, you could bypass the FillAttributes method entirely and directly assign the attribute to the property descriptor:
// Assign attribute to property descriptor propDesc.Attributes = new Attribute[] { new RequiredAttribute() };
Depending on the specific scenario and your design preferences, entweder of these approaches should allow you to add attributes to properties at runtime without encountering the "Collection was of a fixed size" exception.
The above is the detailed content of How to Add Validation Attributes to Runtime Properties in C#?. For more information, please follow other related articles on the PHP Chinese website!