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

时间:2009-04-03 11:29:09

标签: c# .net

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

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

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

7 个答案:

答案 0 :(得分:8)

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

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

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

您认为“文字”的价值是什么?

使用Action&lt;&gt;和Func&lt;&gt;通用类型,你可以(几乎)放在你想要的任何东西。 几乎,因为你无法访问匿名类型的其他属性,例如:

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

答案 1 :(得分:5)

你绝对可以,与代表们一起:

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

obj.DoSomething();

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

答案 2 :(得分:3)

你不能,至少不能达到.NET 3.5。

答案 3 :(得分:1)

这个怎么样:

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

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

基本上使用Lambda作为代理

答案 4 :(得分:0)

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

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

答案 5 :(得分:0)

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

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

来自反射器:

[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 :(得分:0)

你可以:

// 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();

如果您不想声明委托类型,可以使用System.Func&lt;&gt;:

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