您不能将var 用于返回值或参数类型(或字段)。您只能将它用于局部变量。
Eric Lippert 有一个blog post about why you can't use it for fields。我不确定返回值和参数类型是否有类似的。参数类型当然没有多大意义——编译器从哪里推断出类型?您尝试对参数调用什么方法? (实际上 F# 差不多就是这样,但 C# 更保守。)
不要忘记var 是严格 静态类型 - 它只是让编译器为您推断静态类型的一种方式。它仍然只是一种类型,就像您在代码中输入了名称一样。 (当然,对于匿名类型,您不能这样做,这是该功能的一个动机。)
编辑:有关var 的更多详细信息,您可以在Manning's site 免费下载C# 的第8 章-这包括var 部分。显然我希望你会想买这本书,但没有压力:)
编辑:为了解决您的实际目标,您几乎可以使用通用方法实现所有这些:
public class MyClass
{
public T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
// This is the tricky bit.
return 1.0;
}
else
{
return inValue;
}
}
}
如清单所示,棘手的一点是找出“1”对于任意类型的含义。你可以硬编码一组值,但这有点难看:
public class MyClass
{
private static readonly Dictionary<Type, object> OneValues
= new Dictionary<Type, object>
{
{ typeof(int), 1 },
{ typeof(long), 1L },
{ typeof(double), 1.0d },
{ typeof(float), 1.0f },
{ typeof(decimal), 1m },
};
public static T Fn<T>(T inValue) where T : struct
{
Comparer<T> comparer = Comparer<T>.Default;
T zero = default(T);
if (comparer.Compare(inValue, zero) < 0)
{
object one;
if (!OneValues.TryGetValue(typeof(T), out one))
{
// Not sure of the best exception to use here
throw new ArgumentException
("Unable to find appropriate 'one' value");
}
return (T) one;
}
else
{
return inValue;
}
}
}
恶心 - 但它会工作。然后你可以写:
double x = MyClass.Fn(3.5d);
float y = MyClass.Fn(3.5f);
int z = MyClass.Fn(2);
等