想知道是否有一种缩短此代码的有效方法

时间:2017-06-07 04:59:56

标签: c#

所以我的程序最终会变得相当大,我不想要一大堆可以缩短的代码。以下是我正在寻找一些提示的一个例子:

const getGistsDescriptions = async () => {

  const promiseArray = linksArray.map(url=>axios.get(url));
  
  try {
  
    const gistsDescriptions = (
      await Promise.all(promiseArray)
    ).map(res=>res.data)
    
    this.setState({ gistsDescriptions })
    
  } catch(error) {
    console.error(error)
  }
  

}

代码工作正常但我只是希望在必要时获得一些缩短此代码的提示,任何输入都会受到赞赏。

7 个答案:

答案 0 :(得分:2)

假设您可以使用C#7的新元组:

private Dictionary<string, (string image, List<string> books)> books = new Dictionary<string, (string image, List<string> books)>
{
    { "Programming", ("programming.png", new List<string> { "Visual Basic", "Java", "C#"} ) },
    { "Networking", ("networking.png", new List<string> {"LAN Networks", "Windows Networking", "More About Networking"}) },
    { "Web", ("html.png", new List<string> {"Web Programming", "Javascript", "ASP"}) }
};

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // sets books to the clicked item
    string book = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    if (books.Keys.Contains(book))
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(books[book].image);
        foreach(var b in books[book].books)
        {
           bookListBox.Items.Add(b);
        }
    }
}

但课程可能更好:

public class BookGroup
{
    public string ImagePath {get;set;}
    public List<string> Books {get;}

    public BookGroup(string imagePath, params string[] books)
    {
        ImagePath = imagePath;
        Books = new List<string>(books.Length);
        Books.AddRange(books);
    }
}

现在使用它并没有什么不同,但它正式化了一些可能使这段代码更容易使用的东西,并且如果你还不能使用元组,它是可能的。我本身也可能有一个Book课程,只是为了好玩,但是现在:

private Dictionary<string, BookGroup> books = new Dictionary<string, BookGroup>
{
    { "Programming", new BookGroup("programming.png", "Visual Basic", "Java", "C#")},
    { "Networking", new BookGroup("networking.png","LAN Networks", "Windows Networking", "More About Networking") },
    { "Web", new BookGroup("html.png", "Web Programming", "Javascript", "ASP") }
};

private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    // sets books to the clicked item
    string book = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    if (books.Keys.Contains(book))
    {
        bookListBox.Items.Clear();
        BookGroup bg = books[book];
        selectedPictureBox.Image = Image.FromFile(bg.ImagePath);
        foreach(var b in bg.Books)
        {
           bookListBox.Items.Add(b);
        }
    }
}

无论如何,我肯定有办法从文本文件加载这些...可能是csv,或者甚至是一个小的进程内数据库,以便我可以更新此列表无需重新编译或分发新的程序代码。并且,考虑到这一点,为了将这些数据放在单个文件中的单个结构中,我可能还会重复图像并在每本书中输入,以便我的csv数据如下所示:

Topic,Image,Title
Programming,programming.png,"Visual Basic"
Programming,programming.png,"Java"
Programming,programming.png,"C#"
Networking,networking.png,"LAN Networks"
Networking,networking.png,"Windows Networking"
Networking,networking.png,"More About Networking"
Web,html.png,"Web Programming"
Web,html.png,"Javascript"
Web,html.png,"ASP"

这改变了代码的整个特征。我有点偏颇,但我可能会使用this CSV Parser,再次假设元组我会产生这样的东西:

private List<(string Topic, string ImagePath, string Title)> books;

//In the form load code:
books = EasyCSV.FromFile("bookData.csv").Select(b => (b[0], b[1], b[2])).ToList();

//and finally, in the original selectindexchanged method:
private void bookComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    string topic = bookComboBox.SelectedItem.ToString();
    selectedPictureBox.Visible = true;

    var items = books.Where(b => b.Topic == topic).ToArray();
    if(items.Length > 0)
    {
        bookListBox.Items.Clear();
        selectedPictureBox.Image = Image.FromFile(items[0].ImagePath);
        bookListBox.Items.AddRange(items);
    }
}

答案 1 :(得分:2)

制作对象并使用数据绑定。

public class Book
{
    public BookType BookType { get; set; }
    public string Name { get; set; }
    public string Image { get; set; }
}

public enum BookType
{
    Programming,
    Networking,
    Web,
}

public partial class Form1 : Form
{
    private readonly List<Book> _books = new List<Book>
    {
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "VB" },
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "Java" },
        new Book { Image = "programming.png", BookType = BookType.Programming, Name = "C#" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "LAN Networks" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "Windows Networking" },
        new Book { Image = "networking.png", BookType = BookType.Networking, Name = "More About Networking" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "Web Programming" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "Javascript" },
        new Book { Image = "html.png", BookType = BookType.Web, Name = "ASP" },
    };

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var bookTypes = _books.GroupBy(b => b.BookType).Select(g => g.Key).ToList();

        this.cboBookTypes.DataSource = bookTypes;
    }

    private void cboBookTypes_SelectedIndexChanged(object sender, EventArgs e)
    {
        var bookType = (BookType)this.cboBookTypes.SelectedItem;
        var books = _books.Where(b => b.BookType == bookType).ToList();
        var img = books.First().Image;

        this.imgBook.Image = Image.FromFile(img);
        this.lstBooks.DataSource = books;
        this.lstBooks.DisplayMember = "Name";

    }
}

答案 2 :(得分:1)

如果你在谈论代码的长度,我建议使用switch-case-break-default构造 切换书籍变量。 这不会改善性能

答案 3 :(得分:1)

我没有视觉工作室,所以给你提供改进的要点/建议。

  • switch应优先于if-elseif
  • 来自bookListBox.Items.Clear();块的
  • electedPictureBox.Imageif。使用变量设置图像文件名。

答案 4 :(得分:1)

我认为您应该创建代表图书类别的。然后,您可以简单地遍历所有类别列表并提取必要的信息,如下所示:

function mapDispatchToProps(dispatch) {
  return bindActionCreators({userPositionActions, jobTitleSkillsActions}, dispatch)  
}

...


componentDidMount() {
    this.props.userPositionActions.loadUserPositions());
    var job_title_id = this.props.user_positions[0].job_title_id;
    this.props.jobTitleSkillsActions.loadJobTitleSkills(job_title_id));
  }

答案 5 :(得分:1)

创建一个表示图书清单的类:

public class BookList 
{
  public string ImageName { get; set; }
  public List<string> Items { get;set; }
}

然后创建一个字典来保存这些项目:

Dictionary<string, BookList> bookLists = new Dictionary<string, BookList> 
  {
    { 
       "Programming", 
       new BookList { ImageName = "programming.png", Items = new List<string> { ... } }
    }
    ...
  };

然后将if语句修改为:

if (bookLists.ContainsKey(books))
{
  bookListBox.Items.Clear();
  selectedPictureBox.Image = Image.FromFile(bookLists[books].ImageName);
  foreach (var b in bookLists[books].Items)
  {
     bookListBox.Items.Add(b);
  }
}

答案 6 :(得分:1)

我建议将所有数据保存在配置对象中,然后在执行检查和分配时迭代这些数据。

我会创建一个单独的类来保存每本书的数据:名称,图片文件名和复选框项字符串数组。

然后我会创建该对象的列表,并在表单初始化时手动分配所有数据。

之后,在SelectedIndexChanged事件处理程序中,我将对每个项目进行迭代(for循环)并检查书名是否匹配。如果确实如此,那么我将使用该对象的数据,然后break;循环。