开发者

Why can't I pass an anonymous type as a parameter to a function?

I was trying to do something like below but it doesn't work. Why won't .NET let me do this?

privat开发者_运维百科e void MyFunction(var items)
{
 //whatever
}


Beginning in Visual C# 3.0, variables that are declared at method scope can have an implicit type var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type. The following two declarations of i are functionally equivalent:

var i = 10; // implicitly typed
int i = 10; //explicitly typed

In otherwords, var keyword is only allowed for locally scoped variables.

Source.

A little bit more info here. Basically, when using var you must also initialize the variable to a value on the same line so that the compiler knows what type it is.


Strictly saying, you can pass anonymous type as argument, but you can't access it members in strongly typed way. Use generic type argument inferring:

public static int Foo<T>(T obj)
{
    return obj.GetHashCode();
}

public static void Main()
{
   var anonymousType = new { Id = 2, Name = "Second" };
   var value = Foo(anonymousType);
}


C# is a strongly typed language, the addition of anonymous types didn't alter that.

You could of course pass a variable of type object (or an object array) to the function,

private void MyFunction(object items)
{
  //Typecast to whatever you like here....But frankly this is a "code smell"
}

Perhaps you could tell us what you are trying to achieve, maybe there is a better design.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜