小编Ron*_*nin的帖子

如何避免代码重复?

Output()在两个类Hour和方法中都有相同的代码Day.有没有办法避免它在一个地方而不是两个地方改变代码?

class Program
{
    static void Main(string[] args)
    {
        Hour hour = new Hour("20150715 080000");
        Day day = new Day(hour);

        Console.WriteLine(String.Format("Hour: {0}", hour.Output()));
        Console.WriteLine(String.Format("Day: {0}", day.Output()));
    }
}

public interface IMoment
{
    string OutputMoment();
}

class Hour : IMoment
{
    public string Date;
    public string Time;

    public Hour (string s)
    {
        string[] parts = s.Split(';');
        this.Date = parts[0];
        this.Time = parts[1];
    }

    public string Output()
    {
        return Date + " " + Time;
    } …
Run Code Online (Sandbox Code Playgroud)

.net c# code-duplication

0
推荐指数
1
解决办法
97
查看次数

找不到first时发生InvalidOperationException

我正在尝试按商品名称查找商品。

Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
Run Code Online (Sandbox Code Playgroud)

我希望下一步

if (item == null) // if not found
{
    // not found code
}
Run Code Online (Sandbox Code Playgroud)

...但是当找不到物品时,我得到了InvalidOperationException

首先想到的是

try
{
    Item item = Shop.Items.Values.First(i => i.Name.Contains(partOfName))
}
catch(InvalidOperationException ex)
{
    // not found code
}
Run Code Online (Sandbox Code Playgroud)

最好的处理方法是什么?也许没有try / catch?

编辑。 解:

Item item = Shop.Items.Values.FirstOrDefault(i => i.Name.Contains(partOfName))

if (item == null) // if not found
{
    // not found code
}
Run Code Online (Sandbox Code Playgroud)

c# linq invalidoperationexception

-2
推荐指数
1
解决办法
1918
查看次数