如何在C#中创建一个带有必要内部对象的公共类,以保护程序集信息?

huangapple go评论64阅读模式
英文:

How to create a public class with internal required objects in C# for protecting assembly information?

问题

我正在尝试创建一个具有以下内部必需对象的公共类:

public class Person
{
internal required string? FirstName {get; init;}
internal required string? LastName {get; init;}
}


上述类的原因是我想创建一个将添加到另一个项目的程序集。该项目只能通过类对象访问类成员,并且不会被公开。

采用这种方法的原因是为了保护和安全地保留程序集信息。然而,由于具有公共类和内部对象成员,我遇到了错误。

我希望创建具有内部必需成员的公共类,以便无需为类定义构造函数。
英文:

I am trying to create a public class with internal required objects as follows:

public class Person
{
   internal required string? FirstName {get; init;}
   internal required string? LastName {get; init;}
}

The reason behind the above class is that I want to create an assembly that will be added to another project. The project will only be able to access class members through class object and will not be exposed.

The reason for this approach is to keep assembly information protected and secured. However, I am getting error for having public class and internal object members.

I expect to create Public class with internal required members so that I don't have to define constructor for the classes.

答案1

得分: 0

这是不允许的。您不能在这种情况下使用 required 修饰符。

提案1指出:

> 如果无法在包含类型可见的任何上下文中设置成员,则将成员标记为 required 将引发错误。
>
> - 如果成员是字段,则不能将其标记为 readonly
> - 如果成员是属性,则其 setter 或初始化程序必须至少与成员所在的类型一样可访问。

我建议您改为编写构造函数:

public class Person
{
    internal string? FirstName { get; init; }
    internal string? LastName { get; init; }
    
    public Person(string? firstName, string? lastName) {
        FirstName = firstName;
        LastName = lastName;
    }
}

毕竟,required 并不是完全替代构造函数的魔法。它们之间仍然存在许多区别。有关更多信息,请参见我的答案这里

英文:

This is not allowed. You cannot use a required modifier in this case.

The proposal states:

> It is an error to mark a member required if the member cannot be set
> in any context where the containing type is visible.
>
> - If the member is a field, it cannot be readonly.
> - If the member is a property, it must have a setter or initer at least as accessible as the member's containing type.

I would suggest that you write a constructor instead:

public class Person
{
    internal string? FirstName {get; init;}
    internal string? LastName {get; init;}
    
    public Person(string? firstName, string? lastName) {
        FirstName = firstName;
        LastName = lastName;
    }
}

After all, required is not some magic that entirely replaces constructors. There are still many differences between them. For more info, see my answer here.

huangapple
  • 本文由 发表于 2023年5月22日 10:42:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76302757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定