Error cs0149 требуется имя метода

This repository contains .NET Documentation. Contribute to dotnet/docs development by creating an account on GitHub.

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Compiler Error CS0149

Compiler Error CS0149

07/20/2015

CS0149

CS0149

c3c0e48e-8dba-4ee6-86fd-cbb02c68255c

Compiler Error CS0149

Method name expected

When creating a delegate, specify a method. For more information, see Delegates.

The following sample generates CS0149:

// CS0149.cs  
using System;  
  
delegate string MyDelegate(int i);  
  
class MyClass  
{  
   // class member-field of the declared delegate type  
   static MyDelegate dt;
  
   public static void Main()  
   {  
      dt = new MyDelegate(17.45);   // CS0149  
      // try the following line instead  
      // dt = new MyDelegate(Func2);  
      F(dt);  
   }  
  
   public static string Func2(int j)  
   {  
      Console.WriteLine(j);  
      return j.ToString();  
   }  
  
   public static void F(MyDelegate myFunc)  
   {  
      myFunc(8);  
   }  
}  

I would like to create a lambda expression and invoke it immediately and I would like to avoid creating a delegate; a trivial example1:

int i = (() => 42)();

This produces the error:

CS0149 Method name expected

There are two workarounds:

  • Declare a (local) method:

    int Return42() => 42;
    
    int i = Return42();
    
  • Create a delegate:

    int i = ((Func<int>)(() => 42))();
    

It is possible to create and immediately invoke a lambda expression without creating a delegate and without naming it? And if possible, how can one create such a lambda?


1. In reality it is an async Task that I would like to use instead of Task.ContinueWith (I tried to follow what Stephen Cleary said: you should strive to replace ContinueWith with await); e.g:

Task<int> future = (async () =>
                       (await RetrieveLookupFromFarAway())["42"].First())();

With RetrieveLookupFromFarAway something like:

async Task<ILookup<string, int>> RetrieveLookupFromFarAway()
{
    await Task.Delay(1000);
    return Enumerable.Empty<int>().ToLookup((x) => x.ToString());
}

asked May 31, 2018 at 8:33

Kasper van den Berg's user avatar

2

The concept of a lambda expression only exists as source code. It doesn’t even have a type in itself (just like the null literal doesn’t have a type). It has to be converted to either an expression tree or a delegate: that’s what exists as far as the IL and the CLR are concerned. The compiler has to emit code to create something, and you need to tell it which type you want that to be.

The compiler doesn’t play favourites in terms of delegate types: while it could «know» about Func<T> and use that as a default delegate type for a lambda expression with no parameters, it doesn’t.

The closest you’ll get to what you want is to have a convenience method that you can call accepting a Func<T>, which could either just return the function, or execute it and return the result. For example:

public static Func<T> CreateFunc<T>(Func<T> func) => func;
public static T ExecuteFunc<T>(Func<T> func) => func();

Then you can call it as:

CreateFunc(() => 42)();

or

ExecuteFunc(() => 42);

answered May 31, 2018 at 8:35

Jon Skeet's user avatar

Jon SkeetJon Skeet

1.4m851 gold badges9045 silver badges9133 bronze badges

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using System;
 
using AppodealAds.Unity.Api;
using AppodealAds.Unity.Common;
 
/// <summary>
/// In Charge to display and managed all the UI elements in the game
/// </summary>
public class CanvasManager : MonobehaviourHelper
{
    /// <summary>
    /// Delegate subscribe by the GameManager and triggered when creating a new level (if player win, or if switching manually the levels)
    /// </summary>
    public delegate void CreateGame(int level);
    public static event CreateGame OnCreateGame;
 
 
 
 
    /// <summary>
    /// Facebook url open by the native app on mobile
    /// </summary>
    public string facebookApp = "fb://profile/515431001924232" ;
    /// <summary>
    /// Facebook url open by the web browser if failed to open the native app
    /// </summary>
    public string facebookAddress = "https://www.facebook.com/appadvisory";
 
    AudioSource _music;
    /// <summary>
    /// Audiosource with the music attached (if you add a music to it)
    /// </summary>
    AudioSource music
    {
        get 
        {
            if (_music == null)
                _music = Camera.main.GetComponentInChildren<AudioSource> ();
 
            return _music;
        }
    }
 
    /// <summary>
    /// The level displayed on the top of the game view
    /// </summary>
    public Text m_levelText;
 
    /// <summary>
    /// Change the text of the level displayed on the top of the game view
    /// </summary>
    void SetLevelText(int level)
    {
        this.m_levelText.text = "Уровень " + level.ToString() + " / 1200";
    }
 
    /// <summary>
    /// Reference to the IntroMenu GameObject
    /// </summary>
    public GameObject IntroMenuGO;
 
    public Button buttonNextLevel;
    public Button buttonLastLevel;
    public Button buttonSetting;
    public Button buttonUnlock;
    public Button buttonLike;
    public Button buttonLeaderboard;
    public Button buttonRate;
    public Button buttonShare;
    public Button buttonMoreGames;
    public Button buttonSound;
    public Button buttonLikeIntro;
    public Button buttonLeaderboardIntro;
    public Button buttonRateIntro;
    public Button buttonShareIntro;
    public Button buttonMoreGamesIntro;
    public Button buttonSoundIntro;
    public Button buttonPlayIntro;
    public Button buttonOpenIntro;
 
    /// <summary>
    /// Get the max level the player could play. A level is playable if the player unlock the previous level. for exemple: to player the level 10, the player have to cleared the level 
    /// </summary>
    int maxLevel
    {
        get 
        {
            return PlayerPrefs.GetInt (Constant.LEVEL_UNLOCKED, 1);
        }
    }
 
    /// <summary>
    /// Get the last level the player played
    /// </summary>
    int lastLevel
    {
        get 
        {
            return PlayerPrefs.GetInt (Constant.LAST_LEVEL_PLAYED, 1);
        }
    }
 
 
    /// <summary>
    /// Reference to the setting button who will display some icons with an animation when the player click/tap on the settign button
    /// </summary>
    GridLayoutGroup gridLayoutGroup;
 
 
    void OnEnable()
    {
        GameManager.OnSuccessStart += OnSuccessStart;
        GameManager.OnSuccessComplete += OnSuccessComplete;
        GameManager.OnFailStart += OnFailStart;
        GameManager.OnFailComplete += OnFailComplete;
    }
 
    void OnDisable()
    {
        GameManager.OnSuccessStart -= OnSuccessStart;
        GameManager.OnSuccessComplete -= OnSuccessComplete;
        GameManager.OnFailStart -= OnFailStart;
        GameManager.OnFailComplete -= OnFailComplete;
    }
 
    /// <summary>
    /// Called when GameManager trigger the delegate OnSuccessStart
    /// </summary>
    void OnSuccessStart()
    {
        buttonUnlock.transform.DOScale(Vector3.zero,0.3f);  
    }
 
    /// <summary>
    /// Called when GameManager trigger the delegate OnSuccessComplete. Will create the next level
    /// </summary>
    void OnSuccessComplete()
    {
        PlayNextLevel ();
    }
 
    /// <summary>
    /// Called when GameManager trigger the delegate OnFailStart. Will show the button unlock if a rewarded video is available
    /// </summary>
    void OnFailStart()
    {
        ShowButtonUnlock();
    }
 
    /// <summary>
    /// Called when GameManager trigger the delegate OnFailComplete. Will restart the current level
    /// </summary>
    void OnFailComplete()
    {
        ReplayCurrentLevel (lastLevel);
    }
 
    /// <summary>
    /// Set all the UI In Game Buttons
    /// </summary>
    void SetButtons()
    {
 
        buttonNextLevel.onClick.AddListener (() => {
            ButtonLogic ();
            OnClickedButtonNextLevel();
            ButtonLogic ();
        });
 
        buttonLastLevel.onClick.AddListener (() => {
            ButtonLogic ();
            OnClickedButtonPreviousLevel();
            ButtonLogic ();
        });
 
 
        foreach (Transform t in buttonSetting.transform.parent) 
        {
            if (t.GetComponent<Canvas> () != null)
                t.GetComponent<Canvas> ().sortingOrder = buttonSetting.transform.parent.childCount - t.GetSiblingIndex ();
        }
 
        var g = buttonSetting.transform.parent.gameObject;
 
        g.SetActive (false);
        g.SetActive (true);
 
        gridLayoutGroup = buttonSetting.GetComponentInParent<GridLayoutGroup>();
 
        gridLayoutGroup.spacing = new Vector2(0,-43);
 
        buttonSetting.onClick.AddListener (OnClickedSetting);
 
        buttonUnlock.onClick.AddListener (() => {
            buttonUnlock.transform.DOScale(Vector3.zero,0.3f);
 
 
            
 
            if (Appodeal.isLoaded(Appodeal.REWARDED_VIDEO))
            {
                Appodeal.show(Appodeal.REWARDED_VIDEO)( (bool success) => {
                    if(success)
                    {
                        FindObjectOfType<GameManager>().AnimationCameraSuccess();
                    }
                    else
                    {
                        print("the video is not finished or not displayed");
                    }
                });
            }
        });
 
        buttonUnlock.transform.localScale = Vector3.zero;
 
 
        buttonLike.onClick.AddListener (()=>{
            OnClickedSetting();
            OnClickedLike();
        });
        buttonLikeIntro.onClick.AddListener (OnClickedLike);
 
        buttonLeaderboard.onClick.AddListener (OnClickedLeaderboard);
        buttonLeaderboardIntro.onClick.AddListener (OnClickedLeaderboard);
 
        buttonRate.onClick.AddListener (()=>{
            OnClickedSetting();
            OnClickedRate();
        });
        buttonRateIntro.onClick.AddListener (OnClickedRate);
 
        buttonShare.onClick.AddListener (()=>{
            OnClickedSetting();
            OnClickedShare();
        });
        buttonShareIntro.onClick.AddListener (OnClickedShare);
 
 
        buttonMoreGames.onClick.AddListener (()=>{
            OnClickedSetting();
            OnClickedMoreGame();
        });
        buttonMoreGamesIntro.onClick.AddListener (OnClickedMoreGame);
 
 
        buttonPlayIntro.onClick.AddListener (() => {
            StartTheGame();
            introMenu.AnimationIntroToGame(()=>{
                introMenu.gameObject.SetActive(false);
            });
        });
 
        buttonOpenIntro.onClick.AddListener (() => {
            OnClickedSetting();
            introMenu.gameObject.SetActive(true);
            introMenu.AnimationGameToIntro(()=>{
            });
        });
 
 
        int soundOn = PlayerPrefs.GetInt(Constant.SOUND_ON,1);
 
        if (soundOn == 0) 
        {
            music.Stop ();
            buttonSound.transform.GetChild (0).gameObject.SetActive (false);
            buttonSound.transform.GetChild (1).gameObject.SetActive (true);
 
            buttonSoundIntro.transform.GetChild (1).gameObject.SetActive (false);
            buttonSoundIntro.transform.GetChild (2).gameObject.SetActive (true);
        }
        else 
        {
            music.Play ();
            buttonSound.transform.GetChild (0).gameObject.SetActive (true);
            buttonSound.transform.GetChild (1).gameObject.SetActive (false);
 
            buttonSoundIntro.transform.GetChild (1).gameObject.SetActive (true);
            buttonSoundIntro.transform.GetChild (2).gameObject.SetActive (false);
        }
 
        buttonSound.onClick.AddListener (()=>{
            OnClickedSetting();
            OnClickedSound();
        });
        buttonSoundIntro.onClick.AddListener (OnClickedSound);
    }
 
    /// <summary>
    /// Turn on/off the sounds in the game
    /// </summary>
    void OnClickedSound()
    {
        int soundOn = PlayerPrefs.GetInt(Constant.SOUND_ON,1);
 
        if (soundOn == 1) 
        {
            music.Stop ();
            PlayerPrefs.SetInt (Constant.SOUND_ON, 0);
            buttonSound.transform.GetChild (0).gameObject.SetActive (false);
            buttonSound.transform.GetChild (1).gameObject.SetActive (true);
 
            buttonSoundIntro.transform.GetChild (1).gameObject.SetActive (false);
            buttonSoundIntro.transform.GetChild (2).gameObject.SetActive (true);
        }
        else 
        {
            music.Play ();
            PlayerPrefs.SetInt (Constant.SOUND_ON, 1);
            buttonSound.transform.GetChild (0).gameObject.SetActive (true);
            buttonSound.transform.GetChild (1).gameObject.SetActive (false);
 
            buttonSoundIntro.transform.GetChild (1).gameObject.SetActive (true);
            buttonSoundIntro.transform.GetChild (2).gameObject.SetActive (false);
        }
 
 
        PlayerPrefs.Save();
    }
 
    /// <summary>
    /// Open the buttons menu in the game
    /// </summary>
    void OnClickedSetting()
    {
        buttonSetting.enabled = false;
 
        float startvalue = 10;
        float endvalue = -43;
 
        if(gridLayoutGroup.spacing.y == -43)
        {
            startvalue = -43;
            endvalue = 10;
 
            buttonSetting.transform.DORotate ( new Vector3(0, 0, 360), 1, RotateMode.FastBeyond360);
        }
        else
        {
            buttonSetting.transform.DORotate ( new Vector3(0, 0, -360), 1, RotateMode.FastBeyond360);
        }
 
 
 
        DOVirtual.Float(startvalue, endvalue, 1, (float value) => {
            gridLayoutGroup.spacing = new Vector2(0,value);
        }).OnComplete(() => {
            buttonSetting.enabled = true;
        });
    }
 
    /// <summary>
    /// Open the like page. Please define your URL here
    /// </summary>
    void OnClickedLike()
    {
        Debug.Log ("TODO: replace your like links here");
 
        float startTime;
        startTime = Time.timeSinceLevelLoad;
 
        //open the facebook app
        Application.OpenURL(facebookApp);
 
        if (Time.timeSinceLevelLoad - startTime <= 1f)
        {
            //fail. Open safari.
            Application.OpenURL(facebookAddress);
        }
    }
 
    /// <summary>
    /// Call the leaderboard. Please define your methods here.
    /// </summary>
    void OnClickedLeaderboard()
    {
        var leaderboard = FindObjectOfType<LeaderboardManager>();
        if(leaderboard != null)
            leaderboard.ShowLeaderboardUI();
    }
 
    /// <summary>
    /// Call the share method. Please define your methods here.
    /// </summary>
    /// 
    void OnClickedShare()
    {
        Debug.Log ("TODO: put your share code here");
    }
 
    /// <summary>
    /// Call the rate method of the RateManager. If yhe player click on it, we display immediately the pop up of the RateManager by the method PromptPopup
    /// </summary>
    void OnClickedRate()
    {
        FindObjectOfType<RateUsManager>().PromptPopup();
    }
 
 
    /// <summary>
    /// Open a link to your games (exemple: App Store Developer page). Please put your own URL here.
    /// </summary>
    void OnClickedMoreGame()
    {
        Debug.Log ("TODO: replace the link here");
 
        Application.OpenURL ("https://play.google.com/store/apps/details?id=com.pho3nixcorporation.blotnoads");
    }
 
    void Awake()
    {
        Application.targetFrameRate = 60;
        if (!PlayerPrefs.HasKey (Constant.LAST_LEVEL_PLAYED)) {
            PlayerPrefs.SetInt (Constant.LAST_LEVEL_PLAYED, 1);
        } 
 
        if (!PlayerPrefs.HasKey (Constant.LEVEL_UNLOCKED)) {
            PlayerPrefs.SetInt (Constant.LEVEL_UNLOCKED, 1);
        } 
 
        PlayerPrefs.Save ();
 
    
 
        SetButtons ();
    
 
        ButtonLogic ();
 
 
        IntroMenuGO.SetActive (true);
    }
 
 
    /// <summary>
    /// Display the next and/or last button (the arrow around the level at the top of the screen)
    /// </summary>
    void ButtonLogic()
    {
 
        if (lastLevel == 1)
            SetButtonActive(buttonLastLevel,false);
        else
            SetButtonActive(buttonLastLevel,true);
 
        if(lastLevel >= maxLevel)
            SetButtonActive(buttonNextLevel,false);
        else
            SetButtonActive(buttonNextLevel,true);
    }
 
    /// <summary>
    /// Activate and enable - or not - buttons
    /// </summary>
    void SetButtonActive(Button b,bool isActive)
    {
        Color c = b.GetComponent<Image> ().color;
 
        if (isActive) {
            b.GetComponent<Image> ().color = new Color(c.r,c.g,c.b,1f);
            b.interactable = true;
        }  else {
            b.GetComponent<Image> ().color = new Color(c.r,c.g,c.b,0f);
            b.interactable = false;
        }
 
    }
 
    /// <summary>
    /// Call StartTheGameCorout 
    /// </summary>
    public void StartTheGame()
    {
        StartCoroutine ("StartTheGameCorout");
    }
 
    /// <summary>
    /// Start PlayLevel method at the next frame
    /// </summary>
    IEnumerator StartTheGameCorout()
    {
        yield return 0;
 
        PlayLevel (lastLevel);
    }
 
    /// <summary>
    /// When the player failed, we show an unlock button ONLY IF there is a rewarded video available
    /// </summary>
    void ShowButtonUnlock()
    {
        bool isReadyRewardedVideo = false;
 
        isReadyRewardedVideo = Appodeal.isLoaded(Appodeal.REWARDED_VIDEO);
        
                if (isReadyRewardedVideo)
        {
            if (buttonUnlock.transform.localScale.x == 1) {
                buttonUnlock.transform.DOScale (Vector3.one * 1.5f, 0.3f).SetLoops (6, LoopType.Yoyo);
            } else {
                buttonUnlock.transform.DOScale (Vector3.one, 0.3f);
            }
        }
    }
 
    /// <summary>
    /// Run the level logic on the UI side
    /// </summary>
    private void PlayLevel(int level)
    {
        SetLevelText (level);
 
        if(level > maxLevel)
            PlayerPrefs.SetInt (Constant.LEVEL_UNLOCKED, level);
 
        PlayerPrefs.SetInt (Constant.LAST_LEVEL_PLAYED, level);
 
        PlayerPrefs.Save ();
 
        ButtonLogic ();
 
        if(OnCreateGame != null)
            OnCreateGame(level);
    }
 
    /// <summary>
    /// Method called when the player clicked on the left arrow on the left of the level text on the top of the screen during the game
    /// </summary>
    private void OnClickedButtonPreviousLevel()
    {
        int last = lastLevel;
 
        last--;
 
        if (last < 1)
            last = 1;
 
        Camera.main.transform.DOMove (new Vector3 (-50, Camera.main.transform.position.y, -10), 0.3f).OnComplete (() => {
            Camera.main.transform.position = new Vector3 (50, Camera.main.transform.position.y, -10);
            Camera.main.orthographicSize = 20f;
            SetLevelText (last);
 
            PlayLevel (last);
            Camera.main.transform.DOMove (new Vector3 (0, Camera.main.transform.position.y, -10), 0.3f).OnComplete (() => {
            });
        });
 
 
    }
    /// <summary>
    /// Method called when the player clicked on the right arrow on the roght of the level text on the top of the screen during the game
    /// </summary>
    private void OnClickedButtonNextLevel()
    {
        PlayNextLevel ();
 
    }
 
    /// <summary>
    /// Method called when the player failed and so ... we replay the current level
    /// </summary>
    private void ReplayCurrentLevel(int level)
    {
        Camera.main.transform.DOMove (new Vector3 (0, Camera.main.transform.position.y, -10), 0.3f).OnComplete (() => {
            PlayLevel (level);
        });
 
    }
 
    /// <summary>
    /// Method called when the player have to play the next level (if the current level is cleared, or if the payer taps/Clicks on the next button or if the player see a rewarded video to unlock the current level
    /// </summary>
    private void PlayNextLevel()
    {
        int last = lastLevel;
 
        last++;
 
        Camera.main.transform.DOMove (new Vector3 (50, Camera.main.transform.position.y, -10), 0.3f).OnComplete (() => {
 
            Camera.main.transform.position = new Vector3 (-50, Camera.main.transform.position.y, -10);
 
            Camera.main.orthographicSize = 20f;
 
            SetLevelText (last);
 
            PlayLevel (last);
 
            Camera.main.transform.DOMove (new Vector3 (0, Camera.main.transform.position.y, -10), 0.3f).OnComplete (() => {
            });
        });
    }
    void Start()
    {
        String appKey = "dd241bc31bde3ab2369aa13e6680311d500dfce2c36c64f5";
        Appodeal.initialize(appKey, Appodeal.INTERSTITIAL | Appodeal.NON_SKIPPABLE_VIDEO | Appodeal.BANNER | Appodeal.REWARDED_VIDEO);
    }
}

Понравилась статья? Поделить с друзьями:
  • Error cs0149 method name expected
  • Error cs0139 no enclosing loop out of which to break or continue
  • Error cs0126 an object of a type convertible to int is required
  • Error cs0122 юнити
  • Error cs0122 unity