If you create a function, which should make the use of typeconversions more easy, but it maybe leads to more errors, would implement it globally, and what may speaks against it - when the readability seems to have improved?

For (a simple) example:

public static T EnforceConversion<T>(this object Result)
{
    return (T)System.Convert.ChangeType(Result, typeof(T));
}

This is the most plain example I could dig up. The resultion notation is IMHO much more easy to read then the longterm syntax, which needs a specific type put into the method.

You could call it like:

"True".EnforceConversion<Boolean>();

Which I think has it own merits.

Another programmer might end up with the idea, to put into types which can't be more or less implictly casted, would you risk such consequences for your code? The error display will more or less be as handable as it would be in the original call.

Example:

FileInfo MyFile = FileUtilites.SelectFile();
MyFile.EnforceConversion<Boolean>();
有帮助吗?

解决方案

There two reasons why you would want to avoid this.

First, experienced programmers who already know the long syntax will need to learn a new abstraction. While in itself, it isn't a big deal, it is always easier for a newcommers in a project to feel at home with code respecting well-known standards.

Second, you add a dependency in your code. Basically, everywhere you will need a type conversion, you will need to import or rewrite your function.

Even if the code is a bit shorter and have a bit more explicit naming, maintaining this standard throughout the project is likely to cost more than it will benefit.

许可以下: CC-BY-SA归因
scroll top