开发者

Can I make interfaces or abstract classes in C# that declare methods with a parameter of unknown type?

I'm parsing a http GET query string into its components. In trying to make it modular (the number and types of parameters can vary quite a bit), I want to have a Parameter abstract base class or interface that defines whether a property has been set or not, along with a Set method that sets the value. Is there a way to do that with a variable parameter type for the Set method?

The general idea is as follows:

public abstract class Parameter
{
    public bool IsSet { get; protected set; }
    protected Parameter() { IsSet = false; }
    public abstract void Set( --unknown type here-- );
}

A sample parameter child would then be something like:

public class IntParameter : Parameter
{
    public int Value { get; protected set; }
    public void Set(int value)
    {
        Value = value;
        IsSet = true;
    }
}

With this kind of structure I could then toss each query parameter into its appropriate strongly typed class, but still ensure that all of them are acting consistently. The reason for the IsSet property i开发者_如何学编程s to be able to check if the parameter has been set or not, since some parameters don't have any 'safe' values that I would know for sure weren't intentionally passed. If a value is not set, then it would get a default value stuck into it instead.

Looking at the problem, I doubt it can be handled as I want to implement it, but the example should get the idea across about what I'd like to be able to do.

Are there any suggestions on how to best handle it. I wouldn't be surprised if there were a handy design pattern or common way of doing it, but I haven't managed to Google one up.

The options I see off hand are:

  • Don't use inheritance and rely on convention instead for consistency. I most likely wouldn't need to process these through list iterations or such, though if I found a way to do it, it might open some new ideas or opportunities.
  • Use an object parameter and then do some typeof() and switch magic in some way, though that strikes me as very ugly, and non-polymorphic, so to speak.

Any other ideas? :)


Are you maybe looking for something like this

public abstract class Parameter<T>
{ 
    public bool IsSet { get; protected set; } 
    protected Parameter() { IsSet = false; } 
    public abstract void Set(T value);
    public T Value;
}
public class IntParameter : Parameter<int>
{
    public override void Set(int value)
    {
        Value = value;
        IsSet = true;
    }
}

Have a look at An Introduction to C# Generics

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜