2

出于好奇,有没有办法编写一个方法,例如:

public static MyType Parse(string stringRepresentation, [Internal] bool throwException = true)
{
// parsing logic here that conditionally throws an exception or returns null ...
}

public static MyType TryParse(string stringRepresentation)
{
return this.Parse(stringRepresentation, true);
}

我想在内部减少代码冗余,但仍然符合例如 (Try)Parse() 的 BCL 方法签名,但如果 c# 编译器在这种情况下可以生成第二个内部方法,那就太好了。

这已经以某种方式可能了吗?到目前为止找不到任何东西。

4

2 回答 2

3

我不知道你可以,但这不会给你同样的结果吗?

public MyType Parse(string stringRepresentation)
{
    return this.Parse(stringRepresentation, true);
}

internal MyType Parse(string stringRepresentation, bool throwException = true)
{
    // parsing logic here that conditionally throws an exception or returns null ...
}
于 2011-01-03T13:00:47.003 回答
1

我知道这是一个有点晚的答案,但它可能对其他人有帮助。

您可以使用AttributeTargets.Parameter这里是 msdn 链接)来装饰您的属性类,这正是您正在寻找的。

示例属性:

[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)]
public class InternalAttribute : Attribute
{
    // attribute code goes here
}

属性的用法:

public void Foo([Internal] type_of_parameter parameter_name)
{
      //code
}
于 2012-07-12T12:24:14.203 回答