C#如何高效移除类对象属性值中的特殊字符(非反射方案)
Great question! Dealing with 200+ properties manually is definitely a nightmare, and avoiding reflection makes total sense if you care about runtime performance. Here are some solid alternatives I’ve used in similar production scenarios:
1. C# Source Generators (Compile-Time Code Generation)
This is my top recommendation—no runtime reflection overhead, and it auto-generates all the cleanup code you need.
You can build a custom source generator that scans your target class during compilation, identifies all string properties (or any property type you need to clean), and generates an extension method like CleanSpecialCharacters() that handles every property individually.
The generated code will look something like this (completely static, no reflection):
public static class YourClassCleanupExtensions { public static void CleanSpecialCharacters(this YourClass instance) { if (instance == null) return; instance.FirstName = instance.FirstName?.StripSpecialChars(); instance.LastName = instance.LastName?.StripSpecialChars(); // ... Auto-generated lines for all 200+ properties } }
At runtime, you just call yourClassInstance.CleanSpecialCharacters()—it’s as fast as writing every line manually. Plus, if you add/remove properties later, the generator will update the code automatically on the next build.
2. T4 Text Templates (Pre-Build Code Generation)
If source generators feel too involved, T4 templates are a simpler pre-build alternative. You can write a template that uses design-time reflection to inspect your class, then outputs a static cleanup method with all property handling logic.
The template runs when you build your project, so you get a compiled C# method with zero runtime overhead. It’s less flexible than source generators but easier to set up for one-off scenarios.
3. JSON Converter Interception (If Using Serialization)
If you’re receiving the data via JSON (e.g., from an API), you can hook into the deserialization process to clean strings automatically. Both System.Text.Json and Newtonsoft.Json support custom converters for this.
Here’s an example with System.Text.Json:
public class SanitizedStringConverter : JsonConverter<string> { public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { var rawValue = reader.GetString(); return rawValue?.StripSpecialChars(); // Your cleanup logic here } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { writer.WriteStringValue(value); } }
Then register the converter when deserializing:
var serializerOptions = new JsonSerializerOptions(); serializerOptions.Converters.Add(new SanitizedStringConverter()); var yourInstance = JsonSerializer.Deserialize<YourClass>(apiResponse, serializerOptions);
This approach requires zero code changes to your class itself and works seamlessly with existing serialization workflows.
4. IDE-Powered Manual Code Generation
If you want to avoid build-time tools entirely, use your IDE’s refactoring tools to generate the cleanup code quickly. For example:
- In Visual Studio, write the cleanup line for one property, then use Ctrl+R, Ctrl+R (Refactor > Rename) to duplicate and modify the line for every property.
- With ReSharper, use the Duplicate and Modify feature to batch-create all property handling lines in seconds.
It’s a one-time effort, but the result is a static method with optimal runtime performance.
Final Notes
- For long-term maintainability and performance, source generators are the gold standard.
- If serialization is part of your workflow, the converter method is the most low-fuss option.
- T4 templates are a middle ground for simpler projects where source generators feel overkill.
内容的提问来源于stack exchange,提问作者Chow

