.Net 参数属性使命名/可选参数仅在内部/私有可见?

发布于 2024-10-10 06:32:14 字数 459 浏览 6 评论 0原文

出于好奇,有没有一种方法可以编写这样的方法:

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# 编译器在这种情况下可以生成第二种内部方法会很好。

这已经有可能了吗?到目前为止找不到任何东西。

Out of curiosity, is there a way to write a method e.g. like this:

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);
}

I want to cut down code redundancies internally, but remain compliant to e.g. BCL method signatures for (Try)Parse() but if the c# compiler could in this case generate a second, internal method that would be nice.

Is that already somehow possible? Couldn't find anything so far.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

寂寞清仓 2024-10-17 06:32:14

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

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 ...
}

I'm not aware that you can, but wouldn't this give you the same result?

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 ...
}
゛清羽墨安 2024-10-17 06:32:14

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

您可以使用 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
}

I know this is a bit late answer, but it might be of help to somebody else.

You can decoreate your attribute class with AttributeTargets.Parameter (here is the msdn link) which is exactly what you are looking for.

A sample attribute:

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

Usage of the attribute:

public void Foo([Internal] type_of_parameter parameter_name)
{
      //code
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文