只在另一个类中使用一个类

本文关键字:一个 另一个 | 更新日期: 2023-09-27 18:01:27

        public class ClientData : IEquatable<ClientData>
        {
            public String CustomerName { get; set; }
            public int CustomerId { get; set; }        
            public bool Equals(ClientData other)
            {
                if (other == null) return false;
                return (CustomerName == other.CustomerName && CustomerId == other.CustomerId);
            }
            public override int GetHashCode()
            {
                int hash = 23;
                hash = hash * 31 + CustomerName.GetHashCode();
                hash = hash * 31 + CustomerId.GetHashCode();
                return hash;
            }
        }

public class Service
{
    ....
}

我正在寻找一种方法来使用我的ClientData,但只能在我的服务类中,即只有服务类知道ClientData类的存在,并可以正常使用它的方法

只在另一个类中使用一个类

您可以将其设置为嵌套类,例如:

public class Service
{
    private class ClientData : IEquatable<ClientData>
    {
       ...
    }
}

使CientData成为Serviceprivate嵌套类:

public class Service
{
    private class ClientData
    {
        // ...
    }
}

通过使ClientData成为Service的嵌套类,如下所示,Service可以创建ClientData的实例并访问其所有public的方法,但不能将其公开暴露给其他类,并且其他类不能实例化ClientData

public class Service
{
    private class ClientData : IEquatable<ClientData>
    {
        ...
    }
    ...
    private ClientData _clientData = new ClientData();
}

您可以使ClientData类嵌套在Service类中,或者使ClientData类protected并将它们放在同一个程序集中。