Fixed Array As A Parameter
I have a web service th开发者_运维问答at has an array as a parameter. The problem is I only want to let the user send me an array of 15 entries. Of course if they sent me a bigger array I could write code to only take the first 15, but I dont want to do that. I would like to let the user understand we need 15 and only 15 entries and no more.
The only way I know to initialize an array to a fixed value is instantiate it and I cannot do that as a parameter.
Maybe an array as a parameter isnt the best option? Any Ideas?
You can't really control the array length of the input to your operation, but you can add some dynamic validation (i.e., throw an ArgumentException if a user passes an array of a different length). Another option would be to simply have 15 parameters to your operation, but that may not be something too readable if the parameters are related and an array would make more sense.
In the WSDL/XSD for the service you could specify minOccurs
and maxOccurs
of 15. As in:
<xsd:element name="item" minOccurs="15" maxOccurs="15">
<xsd:complexType>
...
</xsd:complexType>
</xsd:element>
You could throw an ArgumentException if the array size is incorrect.
The only language features here would be
1. An argument list
public void Foo<T>(T t1, T t2, T t3, T t4, T t5, T t6, T t7, T t8, T t9, T t10, T t11, T t12, T t13, T t14, T t15)
{
internalFoo(t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15);
}
private void internalFoo(params T[] arr)
{
// profit
}
2. A struct as Parameter Object Pattern
struct FooParams<T>
{
public T t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15;
}
public void Foo<T>(FooParams<T> fooParams)
{
// profit
}
3. C# 4.0 Tuples, you'd be nesting tuples with the Tuple<...,Rest>
style of declaration because the framework library only goes to 8-ary tuples (octuples?)
you can provide description of the function of webservice, to let the user know that only 15 elements will be considered, if use tries to overwhelm that limit, throw exception of argument or your own custom exception... otherwise no other way to do it.
You could use Contract.Requires(arg.Length==15)
and hope the static checker is/will be good enough to catch user errors.
Or you can create a class wrapping an array that it owns. Since the class owns and creates the array it can control its size.
I prefer the first way in most situations. Sometimes you have to live with runtime errors.
精彩评论