浅谈c#开发者应该了解的15个特性

编程入门 行业动态 更新时间:2024-10-21 16:22:44
1. obsoleteattribute

obsoleteattribute 适用于除组件、模块、参数和返回值以外的所有程序元素。将元素标记为 obsolete,可以通知用户该元素将在未来的版本中删除。iserror- 设置为 true,编译器将在代码中使用这个属性时,提示错误。

public static class obsoleteexample{ // mark orderdetailtotal as obsolete. [obsoleteattribute("this property (depricatedorderdetailtotal) is obsolete. use invoicetotal instead.", false)] public static decimal orderdetailtotal { get { return 12m; } } public static decimal invoicetotal { get { return 25m; } } // mark calculateorderdetailtotal as obsolete. [obsoleteattribute("this method is obsolete. call calculateinvoicetotal instead.", true)] public static decimal calculateorderdetailtotal() { return 0m; } public static decimal calculateinvoicetotal() { return 1m; }}

如果我们在代码中使用上述类,则会显示错误和警告。

console.writeline(obsoleteexample.orderdetailtotal);console.writeline( );console.writeline(obsoleteexample.calculateorderdetailtotal());

官方文档-msdn.microsoft/en-us/library/system.obsoleteattribute.aspx

2. 使用 defaultvalueattribute 为 c# 自动实现的属性设置默认值

defaultvalueattribute 可以指定属性的默认值。你可以使用 defaultvalueattribute 创建任意一个值。成员的默认值通常是其初始值。

这个属性不能用于使用特定的值自动初始化对象成员。因此,开发者必须在代码中设置初始值。

public class defaultvalueattributetest{ public defaultvalueattributetest() { // use the defaultvalue property of each property to actually set it, via reflection. foreach (propertydescriptor prop in typedescriptor.getproperties(this)) { defaultvalueattribute attr = (defaultvalueattribute)prop.attributes [typeof(defaultvalueattribute)]; if (attr != null) { prop.setvalue(this, attr.value); } } } [defaultvalue(25)] public int age { get; set; } [defaultvalue("anton")] public string firstname { get; set; } [defaultvalue("angelov")] public string lastname { get; set; } public override string tostring() { return string.format("{0} {1} is {2}.", this.firstname, this.lastname, this.age); }}

自动实现的属性通过反射在类的构造函数中实现初始化。代码遍历类的所有属性,并将它们设置为默认值。

官方文档-msdn.microsoft/zh-cn/library/systemponentmodel.defaultvalueattribute.aspx

3. debuggerbrowsableattribute

debuggerbrowsableattribute 用于确定是否需要以及如何实现在调试器变量窗口中显示成员变量。

public static class debuggerbrowsabletest{ private static string squirrelfirstnamename; private static string squirrellastnamename; // the following debuggerbrowsableattribute prevents the property following it // from appearing in the debug window for the class. [debuggerbrowsable(debuggerbrowsablestate.never)] public static string squirrelfirstnamename { get { return squirrelfirstnamename; } set { squirrelfirstnamename = value; } } [debuggerbrowsable(debuggerbrowsablestate.collapsed)] public static string squirrellastnamename { get { return squirrellastnamename; } set { squirrellastnamename = value; } }}

官方文档-msdn.microsoft/zh-cn/library/system.diagnostics.debuggerbrowsableattribute.aspx

4. ??运算符

当左操作数非空时,??运算符返回左边的操作数,否则返回右边的操作数。??运算符定义为,将可空类型分配给非空类型时要返回的默认值。

int? x = null;int y = x ?? -1;console.writeline("y now equals -1 because x was null => {0}", y);int i = defaultvalueoperatortest.getnullableint() ?? default(int);console.writeline("i equals now 0 because getnullableint() returned null => {0}", i);string s = defaultvalueoperatortest.getstringvalue();console.writeline("returns 'unspecified' because s is null => {0}", s ?? "unspecified");

官方文档-msdn.microsoft/zh-cn/library/ms173224(v=vs.80).aspx

5. curry和 partial 方法

curry- 在数学和计算机科学中,currying 是一种将函数的​​评估转换为多个参数(或参数元组)的技术,主要用于评估一系列函数,每个函数都有一个参数。

为了通过 c# 实现,使用扩展方法的功能。

public static class currymethodextensions{ public static func<a, func<b, func<c, r>>> curry<a, b, c, r>(this func<a, b, c, r> f) { return a => b => c => f(a, b, c); }}func<int, int, int, int> addnumbers = (x, y, z) => x + y + z;var f1 = addnumbers.curry();func<int, func<int, int>> f2 = f1(3);func<int, int> f3 = f2(4);console.writeline(f3(5));

不同方法返回的类型可以与var关键字进行交换。

官方文档-en.wikipedia/wiki/currying

partial- 在计算机科学中,partial应用程序(或 partial功能应用程序)是指将一些参数固定到一个函数的过程,从而产生另一个更小的函数。

public static class currymethodextensions{ public static func<c, r> partial<a, b, c, r>(this func<a, b, c, r> f, a a, b b) { return c => f(a, b, c); }}

partial扩展方法的使用比 curry更直接。

func<int, int, int, int> sumnumbers = (x, y, z) => x + y + z;func<int, int> f4 = sumnumbers.partial(3, 4);console.writeline(f4(5));

官方文档-en.wikipedia/wiki/partial_application

6. weakreference

弱引用使得在收集器收集对象时,仍允许应用程序访问该对象。如果你需要这个对象,你仍然可以获得一个强有力的引用,并阻止它被收集。

weakreferencetest hugeobject = new weakreferencetest();hugeobject.sharkfirstname = "sharky";weakreference w = new weakreference(hugeobject);hugeobject = null;gc.collect();console.writeline((w.target as weakreferencetest).sharkfirstname);

如果垃圾收集器没有明确被地调用,那么仍有很大的可能性弱引用会被分配。

官方文档-msdn.microsoft/en-us/library/system.weakreference.aspx

7. lazy<t>

使用延迟初始化,可推迟创建大型资源密集型对象或执行资源密集型任务时,在程序生命周期内创建或执行指定类的发生。

public abstract class threadsafelazybasesingleton<t> where t : new(){ private static readonly lazy<t> lazy = new lazy<t>(() => new t()); public static t instance { get { return lazy.value; } }}

官方文档-msdn.microsoft/en-us/library/dd642331(v=vs.110).aspx

8. biginteger

biginteger 类型是一个不可变类型,它表示一个任意大的整数,理论上它的值没有上限或下限。这种类型与 framework 中的其他整型类型不同,这种类型具有自身 minvalue 和 maxvalue 属性指示的范围。

注意:因为 biginteger 类型是不可变的,并且因为它没有上限或下限,所以对于导致 biginteger 值变得太大的任何操作,都会引发 outofmemoryexception。

string positivestring = "91389681247993671255432112000000";string negativestring = "-90315837410896312071002088037140000";biginteger posbigint = 0;biginteger negbigint = 0;posbigint = biginteger.parse(positivestring);console.writeline(posbigint);negbigint = biginteger.parse(negativestring);console.writeline(negbigint);

官方文档-msdn.microsoft/en-us/library/system.numerics.biginteger(v=vs.110).aspx

9.没有官方文档的c#关键字 (__arglist / __reftype / __makeref / __refvalue)

一些 c# 关键字是没有官方文档的,没有文档的原因可能是这些关键字没有经过充分测试。但是,这些关键字已被 visual studio 编辑器着色并被识别为官方关键字。

你可以使用 __makeref 关键字在变量中创建一个类型化的引用,使用 __reftype 关键字提取由类型化引用表示的变量的原始类型,从 typedreference 中使用 __refvalue 关键字获取参数值,使用 __arglist 访问参数列表。

int i = 21;typedreference tr = __makeref(i);type t = __reftype(tr);console.writeline(t.tostring());int rv = __refvalue( tr,int);console.writeline(rv);arglisttest.displaynumbersonconsole(__arglist(1, 2, 3, 5, 6));

在使用 __arglist 时,需要 arglisttest 类。

public static class arglisttest{ public static void displaynumbersonconsole(__arglist) { argiterator ai = new argiterator(__arglist); while (ai.getremainingcount() > 0) { typedreference tr = ai.getnextarg(); console.writeline(typedreference.toobject(tr)); } }}

参考-www.nullskull/articles/20030114.asp和community.bartdesmet/blogs/bart/archive/2006/09/28/4473.aspx

10. environment.newline

获取当前环境下的换行字符串。

console.writeline("newline: {0} first line{0} second line{0} third line", environment.newline);

官方文档-msdn.microsoft/en-us/library/system.environment.newline(v=vs.110).aspx

11. exceptiondispatchinfo

保留代码中的某个被捕获的异常。你可以使用 exceptiondispatchinfo.throw 方法,这个方法在 system.runtime.exceptionservicesnamespace 中。这个方法可用于引发异常并保留原始堆栈的调用过程。

exceptiondispatchinfo possibleexception = null;try{ int.parse("a");}catch (formatexception ex){ possibleexception = exceptiondispatchinfo.capture(ex);}if (possibleexception != null){ possibleexception.throw();}

被捕获的异常可以在另一个方法或另一个线程中再次抛出。

官方文档-msdn.microsoft/en-us/library/system.runtime.exceptionservices.exceptiondispatchinfo(v=vs.110).aspx

12. environment.failfast()

如果你想在不调用任何 finally 块或终结器的情况下退出程序,可以使用 failfast。

string s = console.readline();try{ int i = int.parse(s); if (i == 42) environment.failfast("special number entered");}finally{ console.writeline("program complete.");}

如果 i 等于 42,该 finally 块将不会被执行。

官方文档-msdn.microsoft/zh-cn/library/ms131100(v=vs.110).aspx

13. debug.assert&debug.writeif&debug.indent

debug.assert用于检查条件,如果条件是 false,则输出消息并显示一个显示调用堆栈的消息框。

debug.assert(1 == 0, "the numbers are not equal! oh my god!");

如果断言在调试模式下失败,则显示下面的警报,其中包含指定的消息。

debug.writeif- 如果判断的结果是 true,则会将有关调试的信息写入 listeners 收集中的跟踪侦听器内。

debug.writelineif(1 == 1, "this message is going to be displayed in the debug output! =)");

debug.indent/debug.unindent– 使得 indentlevel 逐一递增。

debug.writeline("what are ingredients to bake a cake?");debug.indent();debug.writeline("1. 1 cup (2 sticks) butter, at room temperature.");debug.writeline("2 cups sugar");debug.writeline("3 cups sifted self-rising flour");debug.writeline("4 eggs");debug.writeline("1 cup milk");debug.writeline("1 teaspoon pure vanilla extract");debug.unindent();debug.writeline("end of list");

如果想在调试输出窗口中显示 cake的成分,可以使用上面的代码。

官方文档:debug.assert,debug.writeif,debug.indent / debug.unindent

14. parallel.for&parallel.foreach

parallel.for- 执行一个可并行运行迭代的 for 循环。

int[] nums = enumerable.range(0, 1000000).toarray();long total = 0;// use type parameter to make subtotal a long, not an intparallel.for<long>(0, nums.length, () => 0, (j, loop, subtotal) =>{ subtotal += nums[j]; return subtotal;}, (x) => interlocked.add(ref total, x));console.writeline("the total is {0:n0}", total);

interlocked.add方法添加两个整数,并用总和替换第一个整数。

parallel.foreach- 执行可并行运行迭代的 foreach 操作。

int[] nums = enumerable.range(0, 1000000).toarray();long total = 0;parallel.foreach<int, long>(nums, // source collection () => 0, // method to initialize the local variable (j, loop, subtotal) => // method invoked by the loop on each iteration { subtotal += j; //modify local variable return subtotal; // value to be passed to next iteration }, // method to be executed when each partition has completed. // finalresult is the final value of subtotal for a particular partition.(finalresult) => interlocked.add(ref total, finalresult));console.writeline("the total from parallel.foreach is {0:n0}", total);

官方文档:parallel.for和parallel.foreach

15. isinfinity

返回一个值,用于表示某一个数是否为负无穷或正无穷大。

console.writeline("isinfinity(3.0 / 0) == {0}.", double.isinfinity(3.0 / 0) ? "true" : "false");

官方文档-msdn.microsoft/en-us/library/system.double.isinfinity(v=vs.110).aspx

以上就是浅谈c#开发者应该了解的15个特性的详细内容,更多关于c#开发者应该了解的15个特性的资料请关注其它相关文章!

  • 0
  • 0
  • 0
  • 0
  • 0

更多推荐

浅谈c#开发者应该了解的15个特性

本文发布于:2023-06-11 03:50:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/626141.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浅谈   开发者   特性

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!