What are the uses of “using” in C#?

后端 未结 29 2893
有刺的猬
有刺的猬 2020-11-21 07:31

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of

29条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 07:41

    Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:

    namespace HelloWorld
    {
        using AppFunc = Func, List>;
        public class Startup
        {
            public static AppFunc OrderEvents() 
            {
                AppFunc appFunc = (IDictionary events) =>
                {
                    if ((events != null) && (events.Count > 0))
                    {
                        List result = events.OrderBy(ev => ev.Key)
                            .Select(ev => ev.Value)
                            .ToList();
                        return result;
                    }
                    throw new ArgumentException("Event dictionary is null or empty.");
                };
                return appFunc;
            }
        }
    }
    

    This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).

提交回复
热议问题