C#更好地实现JSON文件

标签 c# json winforms

这是家庭作业,所以如果你能帮忙,谢谢你,如果不能,我明白了。

一切都按预期工作。但我觉得我可以更好地实现事情或拥有更清晰的代码。我希望按钮只调用一个读取 JSON 文件的方法,运行查询并发出正确的显示,而无需像我一样复制代码。

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace EmployeePayDataWk4
{
public partial class Employee_Pay_Form : Form
{       

    public Employee_Pay_Form()
    {
        InitializeComponent();            
    }

    private void Employee_Pay_Form_Load(object sender, EventArgs e)
    {
        EmployeeDataGridView.ColumnCount = 8;
        EmployeeDataGridView.Columns[0].Name = "Employee Name";
        EmployeeDataGridView.Columns[1].Name = "Zip Code";
        EmployeeDataGridView.Columns[2].Name = "Age";
        EmployeeDataGridView.Columns[3].Name = "Monthly Gross Pay";
        EmployeeDataGridView.Columns[4].Name = "Department ID";
        EmployeeDataGridView.Columns[5].Name = "Developer Type";
        EmployeeDataGridView.Columns[6].Name = "Annual Taxes";
        EmployeeDataGridView.Columns[7].Name = "Annual Net Pay";            

    }

    private void LoadAllButton_Click(object sender, EventArgs e)
    {
        EmployeeDataGridView.Rows.Clear();
        //Read from JSON file
        string JSONstring = File.ReadAllText("JSON.json");
        List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);

        //Display into DataGridView
        foreach (Employee emp in employees)
        {
            string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
                emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
                string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
                string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
            EmployeeDataGridView.Rows.Add(row);
        }
    }



    private void FTEmployeeButton_Click(object sender, EventArgs e)
    {
        EmployeeDataGridView.Rows.Clear();

        //Read from JSON file
        string JSONstring = File.ReadAllText("JSON.json");
        List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);

        //LINQ Query for FT Employees
        var FTEmp = from emp in employees
                    where emp.GetTaxForm == "W2"
                    select emp;

        //Display into DataGridView
        foreach (Employee emp in FTEmp)
        {
            string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
                emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
                string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
                string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
            EmployeeDataGridView.Rows.Add(row);
        }
    }

    private void ContractEmployeeButton_Click(object sender, EventArgs e)
    {
        EmployeeDataGridView.Rows.Clear();

        //Read from JSON file
        string JSONstring = File.ReadAllText("JSON.json");
        List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);

        //LINQ Query for Contract Employees
        var contractEmp = from emp in employees
                          where emp.GetTaxForm == "1099"
                          select emp;

        //Display into DataGridView
        foreach (Employee emp in contractEmp)
        {
            string[] row = { emp.Name, emp.Zip, emp.Age.ToString(), string.Format("{0:C}", emp.Pay),
                emp.DepartmentId.ToString(), SetDevType(emp.DepartmentId),
                string.Format("{0:C}", emp.CalculateTax(emp.Pay)),
                string.Format("{0:C}", AnnualPay(emp.Pay) - emp.CalculateTax(emp.Pay))};
            EmployeeDataGridView.Rows.Add(row);
        }
    }


    //Method to determine developer type
    string typeName;
    public string SetDevType(int id)
    {
        if (id == 1)
        {
            typeName = "Object-Oriented";
        }
        else if (id == 2)
        {
            typeName = "Scripts";
        }
        else { typeName = "Unknown"; }
        return typeName;
    }

    public double AnnualPay(double amount) => 12 * amount;
}


class Employee : IFilingStatus
{
    public Employee() { }

    public string Name { get; set; }
    public string Zip { get; set; }
    public int Age { get; set; }
    public double Pay { get; set; }
    public int DepartmentId { get; set; }  
    public string GetTaxForm { get; set; }

    public double CalculateTax(double basis)
    {
        double monthlyTax; 

        if ((GetTaxForm == "W2") || (GetTaxForm == "w2"))
        {
            monthlyTax = .07 * basis;
        }
        else
        {
            monthlyTax = 0;
        }
        return 12 * monthlyTax;
    }
    public double AnnualPay(double amount) => 12 * amount;
}

public interface IFilingStatus
{
    double CalculateTax(double basis);
}

}

最佳答案

我会说这一行:

List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);

应该是

IList<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);

this reason .

根据 StyleCop,局部变量、私有(private)字段和参数应为小写驼峰式:

string jsonString = File.ReadAllText("JSON.json");

另一件事是不要重复自己 (DRY)。这几行可以重构为一个单独的方法:

string JSONstring = File.ReadAllText("JSON.json");
        List<Employee> employees = JsonConvert.DeserializeObject<List<Employee>>(JSONstring);

        //LINQ Query for Contract Employees
        var contractEmp = from emp in employees
                          where emp.GetTaxForm == "1099"
                          select emp;

SetDevType中完全可以使用switch/case,性能更好。

string typeName; // why do we need this?
private string SetDevType(int id)
{
    string typeName = string.Empty;
    switch(id){
        case 1: typeName = "Something"; break;
        default: typeName = "Unknown";
    }
    return typeName;
}

类中有些成员不需要公开,比如

public double AnnualPay(double amount) => 12 * amount;

可以

private double AnnualPay(double amount) => 12 * amount;

并且此方法不知何故也在 Employee 类中,它是一个模型类/POCO。 POCO 类通常不包含非属性(尽管有时包含 ToString 和空构造函数)。

关于C#更好地实现JSON文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53382148/

相关文章:

c# - 在 ASP.net 5 MVC 6 中,如何在不同的命名空间中使用相同的 Controller 名称

json - 发生异常 : type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>' in type cast

javascript - 如何为 REST json 数据创建一个基本的 angularjs 页面?

c# - 我如何调用绘画事件?

c# - WPF - DataTrigger 动画不起作用

c# - 对象作为参数传递给另一个类,按值还是按引用?

c# - C#显示未读邮件数量

c# - 保存 Winform 窗体控件状态的最佳方法?

c# - 抽象掉 Main 的框架

java - 如何从Json对象中获取数据?