如何在匿名类型中定义方法?

时间:2021-03-10 07:13:57

How do I go about defining a method, e.g. void doSuff() in an anonymous type? All documentation I can find uses only anonymous restricted basically to property lists. Can I even define a method in an anonymous type?

我如何定义方法,例如void doSuff()在匿名类型?我能找到的所有文档只使用匿名限制,基本上只限于属性列表。我甚至可以用匿名类型定义方法吗?

EDIT: OK, a quick look at very quick answers tells me this is impossible. Is there any way at all to construct a type dynamically and add an anonymous method to a delegate property on that type? I'm looking for a C# way to accomplish what the following JavaScript does:

编辑:好的,快速查看非常快速的答案告诉我这是不可能的。有没有办法动态构造一个类型并将匿名方法添加到该类型的委托属性?我正在寻找一种C#方式来完成以下JavaScript的工作:

...
person.getCreditLimit = function() { ... }
...

7 个解决方案

#1


You absolutely can, with delegates:

你绝对可以和代表一起:

Action action = MethoThatDoesSomething;
var obj = new
          {
              DoSomething = action
          };

obj.DoSomething();

I tried with a lambda in the new { ... } and that didn't work, but the above is totally fine.

我尝试在新的{...}中使用lambda并且没有用,但上面的内容完全正常。

#2


Well, you can. With delegates you just treat methods as data:

好吧,你可以。对于代理人,您只需将方法视为数据:

var myMethods = from x in new[] { "test" }
                select new { DoStuff = new Func<string>(() => x) };

var method = myMethods.First();
var text = method.DoStuff();

What do you think the value of "text" is?

你认为“文本”的价值是什么?

With the Action<> and Func<> generic types you can put (almost) whatever you want in there. Almost, because you cannot for instance access other properties on the anonymous type, like this:

使用Action <>和Func <>泛型类型,您可以(几乎)将任何内容放入其中。几乎,因为您无法访问匿名类型上的其他属性,如下所示:

var myMethods = from x in new[] { "test" }
                select new { Text = x, DoStuff = new Func<string>(() => Text) };

#3


You cant, at least not up to .NET 3.5.

你不能,至少不是.NET 3.5。

#4


What about this:

那这个呢:

        var anonType = new
        {
            FirstName = "James",
            LastName = "Bond",
            FullName = new Action<string, string>(
                (x, y) =>
                    { 
                        Console.WriteLine(x + y );
                    })                
        };

        anonType.FullName("Roger","Moore");

Basically using a Lambda for the delegate

基本上使用Lambda作为代理

#5


You can't. Anonymouse types only contain properties with public get modifiers and overrides of the GetHashCode(), Equals() and ToString().

你不能。 Anonymouse类型仅包含具有公共get修饰符的属性以及GetHashCode(),Equals()和ToString()的覆盖。

var myclass = new { Name = "Andy", Location = "Bellingham", Sector = 0, };

From reflector:

[CompilerGenerated, DebuggerDisplay(@"\{ Name = {Name}, Location = {Location}, Sector = {Sector} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<Name>j__TPar, <Location>j__TPar, <Sector>j__TPar>
{
    // Fields
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Location>j__TPar <Location>i__Field;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Name>j__TPar <Name>i__Field;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Sector>j__TPar <Sector>i__Field;

    // Methods
    [DebuggerHidden]
    public <>f__AnonymousType0(<Name>j__TPar Name, <Location>j__TPar Location, <Sector>j__TPar Sector)
    {
        this.<Name>i__Field = Name;
        this.<Location>i__Field = Location;
        this.<Sector>i__Field = Sector;
    }

    [DebuggerHidden]
    public override bool Equals(object value)
    {
        var type = value as <>f__AnonymousType0<<Name>j__TPar, <Location>j__TPar, <Sector>j__TPar>;
        return ((((type != null) && EqualityComparer<<Name>j__TPar>.Default.Equals(this.<Name>i__Field, type.<Name>i__Field)) && EqualityComparer<<Location>j__TPar>.Default.Equals(this.<Location>i__Field, type.<Location>i__Field)) && EqualityComparer<<Sector>j__TPar>.Default.Equals(this.<Sector>i__Field, type.<Sector>i__Field));
    }

    [DebuggerHidden]
    public override int GetHashCode()
    {
        int num = 0x5fabc4ba;
        num = (-1521134295 * num) + EqualityComparer<<Name>j__TPar>.Default.GetHashCode(this.<Name>i__Field);
        num = (-1521134295 * num) + EqualityComparer<<Location>j__TPar>.Default.GetHashCode(this.<Location>i__Field);
        return ((-1521134295 * num) + EqualityComparer<<Sector>j__TPar>.Default.GetHashCode(this.<Sector>i__Field));
    }

    [DebuggerHidden]
    public override string ToString()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("{ Name = ");
        builder.Append(this.<Name>i__Field);
        builder.Append(", Location = ");
        builder.Append(this.<Location>i__Field);
        builder.Append(", Sector = ");
        builder.Append(this.<Sector>i__Field);
        builder.Append(" }");
        return builder.ToString();
    }

    // Properties
    public <Location>j__TPar Location
    {
        get
        {
            return this.<Location>i__Field;
        }
    }

    public <Name>j__TPar Name
    {
        get
        {
            return this.<Name>i__Field;
        }
    }

    public <Sector>j__TPar Sector
    {
        get
        {
            return this.<Sector>i__Field;
        }
    }
}

#6


You can't. But here is what you could try:

你不能。但这是你可以尝试的:

var test = new { Foo = new Func<string>(() => "hello") };
test.Foo.Invoke();

#7


You can:

// this line should be in class body, not in method
delegate void MyDelegate(); 
var Obj = new {
    MyDel = new MyDelegate(delegate() { MessageBox.Show("yee-haw"); })
};
Obj.MyDel();

If you don't want to declare a delegate type, you can use System.Func<>:

如果您不想声明委托类型,可以使用System.Func <>:

var Obj = new {
    MyFunc = new Func<string>( delegate() { return "yee-haw"; })
};
MessageBox.Show(Obj.MyFunc());

#1


You absolutely can, with delegates:

你绝对可以和代表一起:

Action action = MethoThatDoesSomething;
var obj = new
          {
              DoSomething = action
          };

obj.DoSomething();

I tried with a lambda in the new { ... } and that didn't work, but the above is totally fine.

我尝试在新的{...}中使用lambda并且没有用,但上面的内容完全正常。

#2


Well, you can. With delegates you just treat methods as data:

好吧,你可以。对于代理人,您只需将方法视为数据:

var myMethods = from x in new[] { "test" }
                select new { DoStuff = new Func<string>(() => x) };

var method = myMethods.First();
var text = method.DoStuff();

What do you think the value of "text" is?

你认为“文本”的价值是什么?

With the Action<> and Func<> generic types you can put (almost) whatever you want in there. Almost, because you cannot for instance access other properties on the anonymous type, like this:

使用Action <>和Func <>泛型类型,您可以(几乎)将任何内容放入其中。几乎,因为您无法访问匿名类型上的其他属性,如下所示:

var myMethods = from x in new[] { "test" }
                select new { Text = x, DoStuff = new Func<string>(() => Text) };

#3


You cant, at least not up to .NET 3.5.

你不能,至少不是.NET 3.5。

#4


What about this:

那这个呢:

        var anonType = new
        {
            FirstName = "James",
            LastName = "Bond",
            FullName = new Action<string, string>(
                (x, y) =>
                    { 
                        Console.WriteLine(x + y );
                    })                
        };

        anonType.FullName("Roger","Moore");

Basically using a Lambda for the delegate

基本上使用Lambda作为代理

#5


You can't. Anonymouse types only contain properties with public get modifiers and overrides of the GetHashCode(), Equals() and ToString().

你不能。 Anonymouse类型仅包含具有公共get修饰符的属性以及GetHashCode(),Equals()和ToString()的覆盖。

var myclass = new { Name = "Andy", Location = "Bellingham", Sector = 0, };

From reflector:

[CompilerGenerated, DebuggerDisplay(@"\{ Name = {Name}, Location = {Location}, Sector = {Sector} }", Type="<Anonymous Type>")]
internal sealed class <>f__AnonymousType0<<Name>j__TPar, <Location>j__TPar, <Sector>j__TPar>
{
    // Fields
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Location>j__TPar <Location>i__Field;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Name>j__TPar <Name>i__Field;
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private readonly <Sector>j__TPar <Sector>i__Field;

    // Methods
    [DebuggerHidden]
    public <>f__AnonymousType0(<Name>j__TPar Name, <Location>j__TPar Location, <Sector>j__TPar Sector)
    {
        this.<Name>i__Field = Name;
        this.<Location>i__Field = Location;
        this.<Sector>i__Field = Sector;
    }

    [DebuggerHidden]
    public override bool Equals(object value)
    {
        var type = value as <>f__AnonymousType0<<Name>j__TPar, <Location>j__TPar, <Sector>j__TPar>;
        return ((((type != null) && EqualityComparer<<Name>j__TPar>.Default.Equals(this.<Name>i__Field, type.<Name>i__Field)) && EqualityComparer<<Location>j__TPar>.Default.Equals(this.<Location>i__Field, type.<Location>i__Field)) && EqualityComparer<<Sector>j__TPar>.Default.Equals(this.<Sector>i__Field, type.<Sector>i__Field));
    }

    [DebuggerHidden]
    public override int GetHashCode()
    {
        int num = 0x5fabc4ba;
        num = (-1521134295 * num) + EqualityComparer<<Name>j__TPar>.Default.GetHashCode(this.<Name>i__Field);
        num = (-1521134295 * num) + EqualityComparer<<Location>j__TPar>.Default.GetHashCode(this.<Location>i__Field);
        return ((-1521134295 * num) + EqualityComparer<<Sector>j__TPar>.Default.GetHashCode(this.<Sector>i__Field));
    }

    [DebuggerHidden]
    public override string ToString()
    {
        StringBuilder builder = new StringBuilder();
        builder.Append("{ Name = ");
        builder.Append(this.<Name>i__Field);
        builder.Append(", Location = ");
        builder.Append(this.<Location>i__Field);
        builder.Append(", Sector = ");
        builder.Append(this.<Sector>i__Field);
        builder.Append(" }");
        return builder.ToString();
    }

    // Properties
    public <Location>j__TPar Location
    {
        get
        {
            return this.<Location>i__Field;
        }
    }

    public <Name>j__TPar Name
    {
        get
        {
            return this.<Name>i__Field;
        }
    }

    public <Sector>j__TPar Sector
    {
        get
        {
            return this.<Sector>i__Field;
        }
    }
}

#6


You can't. But here is what you could try:

你不能。但这是你可以尝试的:

var test = new { Foo = new Func<string>(() => "hello") };
test.Foo.Invoke();

#7


You can:

// this line should be in class body, not in method
delegate void MyDelegate(); 
var Obj = new {
    MyDel = new MyDelegate(delegate() { MessageBox.Show("yee-haw"); })
};
Obj.MyDel();

If you don't want to declare a delegate type, you can use System.Func<>:

如果您不想声明委托类型,可以使用System.Func <>:

var Obj = new {
    MyFunc = new Func<string>( delegate() { return "yee-haw"; })
};
MessageBox.Show(Obj.MyFunc());