Вопрос

I have a JSON class object that is an internal class. I'd like to keep it that way to keep other code from trying to create objects of that type since I only want the JSON deserialization code to do that. I can use the class type as a variable, but if I try to return an object of that type I get an inconsistent accessibiliy compiler error because the method is public and the class is internal.

What is the best way to resolve this situation? I guess I could create an interface for the internal class and pass that around, but that means I have to create extra baggage for every JSON class I am using and I'm using a lot of them.

EDIT: I made the change suggested by Jon Skeet and the problem went away. I got into this problem because of the habit of declaring my classes public by default. I'm pointing this out for others that are doing the same thing.

// The internal class.
internal class JsonPetShelters
{

    [JsonProperty("@encoding")]
    public string Encoding { get; set; }

    [JsonProperty("@version")]
    public string Version { get; set; }

    [JsonProperty("petfinder")]
    public Petfinder Petfinder { get; set; }
}

// This method gets the inconsistent accessibility error since
//   JsonPetShelters is an internal class.
public JsonPetShelters GetShelters()
{
    // For example purposes only
    return null;
}
Это было полезно?

Решение

What is the best way to resolve this situation?

You either need to make JsonPetShelters public, or make GetShelters() internal.

So you want to be able to call this method from a different assembly? If so, how would you expect callers to use it, without understanding the return type? If not, why is the method public?

Once you've worked out what you want do achieve in a consistent way, making the change should be simple.

EDIT: As you've said you only want code in the same assembly to be able to call the method, just change it to be internal:

internal JsonPetShelters GetShelters()
{ 
    ...
}

The compile-time error will go away, and you'll no longer be exposing a member you didn't want to expose in the first place.

Другие советы

You can declare the class Constructor explicitly and make it internal, while the class remains public.

That will allow every assembly to use the class, but only your assembly can create instances.

public class JsonPetShelters
{

    [JsonProperty("@encoding")]
    public string Encoding { get; set; }

    [JsonProperty("@version")]
    public string Version { get; set; }

    [JsonProperty("petfinder")]
    public Petfinder Petfinder { get; set; }

    internal JsonPetShelters() {}
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top