簡體   English   中英

如何在匿名類型中定義方法?

[英]How do I define a method in an anonymous type?

我如何定義一個方法,例如匿名類型的void doSuff() 我能找到的所有文檔只使用匿名限制,基本上只限於屬性列表。 我甚至可以用匿名類型定義方法嗎?

編輯:好的,快速查看非常快速的答案告訴我這是不可能的。 有沒有辦法動態構造一個類型並將匿名方法添加到該類型的委托屬性? 我正在尋找一種C#方式來完成以下JavaScript的工作:

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

好吧,你可以。 使用代理,您只需將方法視為數據:

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

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

你認為“文本”的價值是什么?

使用Action <>和Func <>泛型類型,您可以(幾乎)將任何內容放入其中。 幾乎,因為您無法訪問匿名類型上的其他屬性,如下所示:

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

你絕對可以和代表一起:

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

obj.DoSomething();

我嘗試在new { ... }使用lambda但是沒有用,但上面的內容完全沒問題。

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

那這個呢:

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

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

基本上使用Lambda作為代理

你不能。 但這是你可以嘗試的:

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

你不能。 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;
        }
    }
}

您可以:

// 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 <>:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM