开发者

What is the best way to show that the method modifies the argument in c#?

I have a method which besides some other actions also modify one of the arguments. For example:

public void开发者_如何学运维 DoSomeStuffAndModifyList(List<int> list)
{
   ...
   list.Add(newElement);
}

It looks for me that the name of the method is not enough for pointing on this. May be the whole approach is wrong or there could be ref or out used?


Use a descriptive name for your method / arguments

public void FillItems(string foo,IList<Item> itemsToFeed)


Do not use ref unless it is actually necessary.

If your method is

void DoSomething(List<int> list)
{
    list.Add(whatever);
}

Adding ref is not useful. You are doing nothing that requires it, only adding additional complexity for no benefit, and possibly making the method harder to reason about for a maintenance programmer.

Use ref when your method can actually change list by pointing it to something other than the original list. This can be a completely new list, another existing list, or null. And only use ref when you want this change to be visible at the caller.

For your method, explore refactoring it so that maybe adding or removing items from the list is not necessary. After you've done this, absolutely name the method appropriately. After you have done that, utilize the method and parameter summary comments to convey information you think is useful.

/// <summary>
/// Describe the method andhere
/// </summary>
/// <param name="list">Describe what's relevant about the parameter here.</param>

Don't abuse the ref keyword, do appropriate refactoring, do use documentation.


use ObservableCollection<T> and fire CollectionChanged event when it changed http://msdn.microsoft.com/en-us/library/ms668604.aspx

or you can make your method as exentsion method like that

public static List<int> DoSomeStuffAndModifyList(this List<int> list)
{
 ...
 list.Add(newElement);
 return list;
}


How about returning a new list:

public List<int> DoSomeStuff(List<int> list)
{
    ...
    return list.Concat(new[] { newElement });
}


I am slightly confused on your question. Are you asking how to name your methods?

You should break your your actions into different methods. I wouldn't worry to much about the method that calls these actions. As long as it is descriptive enough, that should be fine.

As John Saunders said, split your methods for single responsibility.

public List<int> GetList()
{
   //return list
}

public void ModifyList(List<int> list)
{
  //Modify list, you could return if you wanted to.
}

//Call 2 methods
List<int> list = GetList();
ModifyList(list);


Create an extension method.

public static class ListExtensions
{
    public static void DoSomeStuffAndModifyList(this List<int> list)
    {
       ...
       list.Add(newElement);
    }
)

And to call it:

var gradeList = new List<int>();
gradeList.DoSomeStuffAndModifyList();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜