问题
I need to hide few methods inside a class based on the parameter that is passed to the constructor in c#. How would I do this? Thanks in advance!
More Info: I was part of this GUI development where they had a API with access to registers in a hardware. Now they are releasing a newer hardware so I need to support both old and new one which has a newer API(Mostly duplicate of old one with some old removed and some new registers added).
Moreover, I need to keep this only one class called "API" as we used it in many places. So the idea of using a newer API with a different name was ruled out.
Now finally, I got this idea of including the newer one into old one with just conditionally hiding the registry access methods.
回答1:
You can't toggle the visibility of members..... the best bet is to have different interfaces that hide the members.
public interface IName
{
string Name { get; set; }
}
public interface INumber
{
string PhoneNumber { get; set; }
}
public class Worker : IName, INumber
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
So either use Worker through the IName or the INumber interface and it will hide the other members on the class....
回答2:
I think you might be looking at a re-factor here. Try making a base class with all the methods / properties that behave the same regardless of the parameter, then two child classes which behave differently. Also have a look at the class factory pattern.
回答3:
You will need to restructure the code into multiple classes or interfaces. You can't dynamically change the visibility level of class members based on a parameter value. Members are construction time information not run time.
回答4:
You can't change visibility of methods, but you can pass parameter to the single method and do some logic depending on your parameter by using switch
- case
. But it depends on your method structure.
Try to review your class and change its design. Maybe you can find any design pattern that will help you.
回答5:
You may actually do something alike using Dynamic code generation, although this is more like a hack than actual code that should be used in production.
Maybe if you explain why you need this then you may get more relevant answers.
来源:https://stackoverflow.com/questions/9010500/how-to-hide-functions-within-classes-in-c