C# Friend classes and OOP Composition

2019-03-18 12:46发布

问题:

Given class A, which contains sets of raw data, and class B, which contains a re-organized version (GUI ready) of that data I would like to make the raw data in A visible in B.

Clearly the raw data in class A is contained in private members. I would like to make that data visible in B though the use of something akin to the C++ friend classes method.

How can I approach this?

Thank you.

回答1:

Strictly speaking, you can't define a specific class (or list of classes) that you can expose the data to. You can, however, use the internal access modifier instead of private, which makes the members available to any class in the same assembly.

That being said, you should strongly consider exposing these members through properties rather than fields (which is what I'm guessing you're planning on exposing). Doing this will allow the class to define exactly how that information can be exposed to other classes and what--if anything--should happen when another class changes the data.



回答2:

May be this might help you..

public class A
{
    public A() { }

    public string AccessData(object accessor)
    {
        if (accessor is B)
            return "private_data";
        else
            throw new UnauthorizedAccessException();
    }
}

public class B
{
    public B() { }

    private void AccessDataFromA()
    {
        Console.WriteLine(new A().AccessData(this));
    }
}


回答3:

You could define both in an assembly and mark the fields in A as "internal".

A more OO approach is to provide a set of public methods in A that allow access to the data (or a subset of the data), typically via simple properties.



回答4:

Depending on your structure you may be able to use Partial classes. This would mean that the Data and UI are actually both within the same class, but you have them within different files.

If that doesn't work for you, then you've got internal scoped variables as an alternative or working with Datasets that the UI represents in a more generic manner.



回答5:

The old method (pun intended) would be to define simple getvalue() and setvalue() functions to return that value so that these values would become inaccessible without the use of these functions, in C# these functions are predefined members called properties.

class TestMethod{ 
private int Secret;

get { return Secret;}
set { Secret = value;}
}

The other method is to, as others have stated before me, just use the internal modifier.