.NET框架库中的ref关键字示例

Ran*_*tha 3 .net c#

DateTime.TryParse方法有一个DateTime out参数.

public static bool TryParse(string s, out DateTime result)
Run Code Online (Sandbox Code Playgroud)

ref.NET框架中是否有关键字的这种用法?

Dav*_*d M 7

是的,例如Interlocked.Exchange:各种重载:

public static double Exchange(
ref double location1,
double value
)
Run Code Online (Sandbox Code Playgroud)


Ree*_*sey 5

这用于各种地方.例如,出于性能原因,XNA ref在诸如Matrix.Add之类的方法中使用很多.许多互锁方法都依赖于ref 正确的操作.

话虽这么说,ref是应该尽量少用,根据对类库,这是为什么它不是很常见的设计指南.甚至有一个代码分析警告(CA1045)暗示不使用ref,尽管有理由偶尔压制这个.


svi*_*ick 5

您可以ref使用反射(和LINQ)获取mscorlib 中所有方法的列表:

from type in typeof(object).Assembly.GetExportedTypes()
where !type.IsInterface
from method in type.GetMethods()
where method.GetParameters().Any(
    p => p.ParameterType.IsByRef &&
        !p.GetCustomAttributes(typeof(OutAttribute), false).Any())
select method
Run Code Online (Sandbox Code Playgroud)

过滤掉具有ref参数的方法OutAttribute是必要的,因为这是out参数实际表示的方式.