如何精简C#代码?基于MySQL的电影信息查询应用代码优化需求
Hey there! I totally get dealing with bloated code where the same logic repeats just with different queries and variable names—let's fix that with some smart reuse patterns that'll make your code way easier to maintain. Here's a step-by-step breakdown:
1. Create a Reusable Database Helper Class
First, extract all the repetitive database connection/query logic into a single helper class. This eliminates copying MySqlConnection, MySqlCommand, and reader code every time you need to fetch data.
using MySql.Data.MySqlClient; using System.Collections.Generic; using System.Data; public static class DbHelper { // Reuse the connection string (store this in config for production!) private static readonly string _connectionString = "Server=your_server;Database=your_db;Uid=user;Pwd=password;"; // Generic method to execute a query and map results to a model public static List<T> ExecuteQuery<T>(string sql, Dictionary<string, object> parameters = null, Func<IDataReader, T> mapFunc) { var results = new List<T>(); using (var conn = new MySqlConnection(_connectionString)) using (var cmd = new MySqlCommand(sql, conn)) { // Add parameters if provided if (parameters != null) { foreach (var param in parameters) { cmd.Parameters.AddWithValue(param.Key, param.Value); } } conn.Open(); using (var reader = cmd.ExecuteReader()) { while (reader.Read()) { results.Add(mapFunc(reader)); } } } return results; } }
2. Define Strongly-Typed Models
Instead of using loose DataTables or ad-hoc variables, create model classes for your data. This makes your code more readable and avoids magic strings.
// Movie model public class Movie { public int Id { get; set; } public string Title { get; set; } public int ReleaseYear { get; set; } public string Genre { get; set; } // Add other movie properties as needed } // Actor model public class Actor { public int Id { get; set; } public string Name { get; set; } public string CharacterName { get; set; } // Link to movie if needed public int MovieId { get; set; } }
3. Simplify the UI Logic in Your Form
Now, your form code becomes super clean—no repetitive database setup, just calling our helper methods and binding data. We'll also extract the DataGridView binding into a reusable method.
using System.Collections.Generic; using System.Linq; using System.Windows.Forms; public partial class MovieForm : Form { public MovieForm() { InitializeComponent(); // Load initial movie list into ComboBox LoadMoviesIntoComboBox(); } private void LoadMoviesIntoComboBox() { var movies = DbHelper.ExecuteQuery<Movie>( "SELECT Id, Title FROM Movies", mapFunc: reader => new Movie { Id = reader.GetInt32("Id"), Title = reader.GetString("Title") }); movieComboBox.DisplayMember = "Title"; movieComboBox.ValueMember = "Id"; movieComboBox.DataSource = movies; } private void movieComboBox_SelectedIndexChanged(object sender, EventArgs e) { if (movieComboBox.SelectedValue is int movieId) { // Fetch movie details var movieDetails = DbHelper.ExecuteQuery<Movie>( "SELECT * FROM Movies WHERE Id = @MovieId", parameters: new Dictionary<string, object> { { "@MovieId", movieId } }, mapFunc: reader => new Movie { Id = reader.GetInt32("Id"), Title = reader.GetString("Title"), ReleaseYear = reader.GetInt32("ReleaseYear"), Genre = reader.GetString("Genre") }).FirstOrDefault(); // Fetch cast for the movie var movieCast = DbHelper.ExecuteQuery<Actor>( "SELECT a.Name, c.CharacterName FROM Actors a JOIN Cast c ON a.Id = c.ActorId WHERE c.MovieId = @MovieId", parameters: new Dictionary<string, object> { { "@MovieId", movieId } }, mapFunc: reader => new Actor { Name = reader.GetString("Name"), CharacterName = reader.GetString("CharacterName") }); // Bind data to DataGridViews (or combine into one if needed) BindDataToGridView(movieDetailsGridView, new List<Movie> { movieDetails }); BindDataToGridView(castGridView, movieCast); } } // Reusable method to bind any list to a DataGridView private void BindDataToGridView<T>(DataGridView dgv, List<T> data) { dgv.DataSource = null; dgv.DataSource = data; // Optional: Auto-size columns for better readability dgv.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells); } }
Key Improvements You'll Notice:
- No repeated database code: All connection/query logic lives in
DbHelper—change it once, and all queries benefit. - Strongly-typed data: Models like
MovieandActormake your code self-documenting and avoid runtime errors from misnamed columns. - Clean UI logic: The form code focuses on what it should—handling user interaction and binding data—instead of low-level database stuff.
- Easy to extend: Want to add a new query? Just call
DbHelper.ExecuteQuerywith your SQL and mapping function, no boilerplate.
If you're using a newer version of C#, you could even take this further with async/await versions of the helper methods, or use an ORM like Dapper to simplify the mapping even more—but the above approach is lightweight and perfect for cleaning up existing code without overcomplicating things.
内容的提问来源于stack exchange,提问作者JimmyNeutron

