簡體   English   中英

簡化[C#]

[英]Make simple [C#]

這可能寫的很簡單,代碼在這里:

foreach (var friend in friends)
{
    friend.Value.blockQuote = GetBlockQuote(friend.Value.nick);

    if (friend.Value.photo == "0")
    {
        if (friend.Value.sex == 1)
        {
            var img = new BitmapImage();
            img.BeginInit();
            img.UriSource = new Uri(@"avatars\man.jpg",
                                    UriKind.Relative);
            img.EndInit();
            friend.Value.profilePhoto = img;
        }
        if (friend.Value.sex == 2)
        {
            //da default
            var img = new BitmapImage();
            img.BeginInit();
            img.UriSource = new Uri(@"avatars\woman.jpg",
                                    UriKind.Relative);
            img.EndInit();
            friend.Value.profilePhoto = img;
        }
    }
    else
    {
        var img = new BitmapImage();
        img.BeginInit();
        img.UriSource = new Uri(friend.Value.photo.Replace(@"\", "").Replace(@"s_", ""), UriKind.Absolute);
        img.EndInit();
        friend.Value.profilePhoto = img;
    }
}

突破uri設置部分

foreach (var friend in friends)
{
    friend.Value.blockQuote = GetBlockQuote(friend.Value.nick);

    Uri uri;
    if (friend.Value.photo == "0")
    {
        if (friend.Value.sex == 1)
        {
            uri = new Uri(@"avatars\man.jpg", UriKind.Relative);
        }
        else if (friend.Value.sex == 2)
        {
            //da default
            uri = new Uri(@"avatars\woman.jpg", UriKind.Relative);
        }
        else
        {
            uri = null; // insert error handling here
        }
    }
    else
    {
        uri = new Uri(friend.Value.photo.Replace(@"\", "").Replace(@"s_", ""), UriKind.Absolute);
    }
    var img = new BitmapImage();
    img.BeginInit();
    img.UriSource = uri;
    img.EndInit();
    friend.Value.profilePhoto = img;
}

編輯
注意,if-else-part現在是Refactor-> Extract方法的良好候選者

您可以排除界限

var img = new BitmapImage();
img.BeginInit();

img.EndInit();
friend.Value.profilePhoto = img;

通過將它們放在(對於前者)之前(對於后者)在if / else塊之后。

foreach (var friend in friends)
{
    friend.Value.blockQuote = GetBlockQuote(friend.Value.nick);
    var img = new BitmapImage();
    img.BeginInit();

    if (friend.Value.photo == "0")
    {
        if (friend.Value.sex == 1)
        {
             img.UriSource = new Uri(@"avatars\man.jpg",
        }
        if (friend.Value.sex == 2)
        {
             img.UriSource = new Uri(@"avatars\woman.jpg",
                                                UriKind.Relative);
        }
     }
     else
     {
          img.UriSource = new Uri(friend.Value.photo.Replace(@"\", "").Replace(@"s_", ""), UriKind.Absolute);

     }

     img.EndInit();
     friend.Value.profilePhoto = img;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM