• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# dynamic类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中dynamic的典型用法代码示例。如果您正苦于以下问题:C# dynamic类的具体用法?C# dynamic怎么用?C# dynamic使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



dynamic类属于命名空间,在下文中一共展示了dynamic类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: CleanupSsh

        private static object CleanupSsh(dynamic parm)
        {
            string userRegex = parm["user_regex"].Value;
            string userName = userRegex.Remove(0, 1);
            userName = userName.Remove(userName.Length - 1, 1);
            SshResult sshResult = new SshResult();
            sshResult.Command = "cleanup";
            Logger.Info("Cleaning up SSH");

            try
            {
                WindowsVCAPUsers.DeleteUser(userName);
                File.Delete(Path.Combine(Config.BaseDir, "bosh", "salt", userName + ".salt"));
                Logger.Info("Deleted salt file");
                sshResult.Status = "success";
                Logger.Info("Deleted user for SSH");
                SshdMonitor.StopSshd();
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to delete user " + ex.ToString());
                sshResult.Status = "failed";
            }

            sshResult.IP = null;
            return sshResult;
        }
开发者ID:UhuruSoftware,项目名称:bosh-dotnet,代码行数:27,代码来源:Ssh.cs


示例2: Carrier

		public Carrier(ISemanticTypeStruct protocol, string protocolPath, dynamic signal, ICarrier parentCarrier)
		{
			Protocol = protocol;
			Signal = signal;
			ProtocolPath = protocolPath;
			ParentCarrier = parentCarrier;
		}
开发者ID:keithshort,项目名称:HOPE,代码行数:7,代码来源:Carrier.cs


示例3: CreateNewJob

 public HttpResponseMessage CreateNewJob(dynamic data)
 {
     try
     {
         tblFresherJob jobDetails = new tblFresherJob();
         FresherJobModel fresherJobDetails = JsonConvert.DeserializeObject<FresherJobModel>(JsonConvert.SerializeObject(data.NewJobDetails));
         long publicUserProfileId = JsonConvert.DeserializeObject<long>(JsonConvert.SerializeObject(data.PublicUserProfileId));
         string errorMessage = ValidateJobRequest(jobDetails);
         if (string.IsNullOrEmpty(errorMessage))
         {
             return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, errorMessage);
         }
         tblUser user = _AccountRepository.GetUserDetailsByPublicUserId(publicUserProfileId);
         if (user.UserTypeId != (short)UserType.Organization)
         {
             return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid request");
         }
         jobDetails.Title = fresherJobDetails.title;
         jobDetails.Description = fresherJobDetails.description;
         jobDetails.Salary = fresherJobDetails.salary;
         jobDetails.Location = fresherJobDetails.location;
         jobDetails.UserId = user.UserId;
         _SearchJobsRepository.CreateFresherJob(jobDetails);
         return this.Request.CreateResponse(HttpStatusCode.OK);
     }
     catch (Exception ex)
     {
         return this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
     }
 }
开发者ID:iamlalit,项目名称:searchFresherJobs,代码行数:30,代码来源:JobsAPIController.cs


示例4: SetCharacter

        private object SetCharacter(dynamic parameters)
        {
            var sessionId = Request.Form.SessionId;

            var characterString = Request.Form.Character;

            var character = (Character)JsonConvert.DeserializeObject<Character>(characterString);

            var dataPlayer = CharacterFactory.Players.FirstOrDefault(player => player.Id == character.Id);

            if (!CharacterFactory.PlayerExists(sessionId)) return "Invalid session id.";

            var sessionCharacter = CharacterFactory.GetPlayerCharacter(sessionId);

            if (character.Id != sessionCharacter.Id)
            {
                return null;
            }

            dataPlayer.Destination = character.Destination;

            dataPlayer.LookTarget = character.LookTarget;

            return "Updated " + character.Id;
        }
开发者ID:EricWehrly,项目名称:SoManyZombies,代码行数:25,代码来源:UpdateCharacter.cs


示例5: ordered_hack

        /// <summary>
        /// TODO: Implement as behavior
        /// </summary>
        /// <param name="shape"></param>
        /// <returns></returns>
        private static IEnumerable<dynamic> ordered_hack(dynamic shape) {
            IEnumerable<dynamic> unordered = shape;
            if (unordered == null || unordered.Count() < 2)
                return shape;

            var i = 1;
            var progress = 1;
            var flatPositionComparer = new FlatPositionComparer();
            var ordering = unordered.Select(item => {
                var position = (item == null || item.GetType().GetProperty("Metadata") == null || item.Metadata.GetType().GetProperty("Position") == null)
                                   ? null
                                   : item.Metadata.Position;
                return new { item, position };
            }).ToList();

            // since this isn't sticking around (hence, the "hack" in the name), throwing (in) a gnome 
            while (i < ordering.Count()) {
                if (flatPositionComparer.Compare(ordering[i].position, ordering[i - 1].position) > -1) {
                    if (i == progress)
                        progress = ++i;
                    else
                        i = progress;
                }
                else {
                    var higherThanItShouldBe = ordering[i];
                    ordering[i] = ordering[i - 1];
                    ordering[i - 1] = higherThanItShouldBe;
                    if (i > 1)
                        --i;
                }
            }

            return ordering.Select(ordered => ordered.item).ToList();
        }
开发者ID:akhurst,项目名称:ricealumni,代码行数:39,代码来源:ZoneShapes.cs


示例6: I1

		private int I1( int II, dynamic lI ) {
			int _local_3 = 0;
			while ( II != lI.l( lI.s( lI.y( Il[Il[( ( ".$".i( ( -1 << -1 ) ) | lI.x() ) | 1 )]] ) ), _local_3, 1 ) ) {
				_local_3++;
			};
			return ( _local_3 );
		}
开发者ID:wangxd1213,项目名称:kcapi_in_csharp_impl,代码行数:7,代码来源:PortAPI.cs


示例7: UnInstall

        public object UnInstall(dynamic args)
        {
            string packageId = args.packageId;

            Context.PackageManager.UnInstall(packageId);
            return null;
        }
开发者ID:ZooLab,项目名称:thinking-home,代码行数:7,代码来源:PackagesPlugin.cs


示例8: Update

        public object Update(dynamic args)
        {
            string packageId = args.packageId;

            Context.PackageManager.Update(packageId);
            return null;
        }
开发者ID:ZooLab,项目名称:thinking-home,代码行数:7,代码来源:PackagesPlugin.cs


示例9: private_dynamic_methods_and_functions

        void private_dynamic_methods_and_functions()
        {
            act = () => gemini = new PrivateGemini();

            it["private function that take in no parameters and return dynamic are publicly accessible"] = () =>
                (gemini.HelloString() as string).should_be("hello");

            it["original exception is retained for private functions"] = expect<InvalidOperationException>(() => gemini.HelloException());

            it["private function that take in dynamic and return dynamic are publicly accessible"] = () =>
                (gemini.Hello("Jane") as string).should_be("hello Jane");

            it["private function that take in dynamic and return dynamic retain exception"] =
                expect<InvalidOperationException>(() => gemini.HelloException("Jane"));

            it["private delegate that take in dynamic can interperet generic parameters"] = () =>
                (gemini.HelloFullName(firstName: "Jane", lastName: "Doe") as string).should_be("hello Jane Doe");

            it["private method that takes in no parameters is publically accessible"] = () =>
            {
                gemini.Alter();

                ((bool)gemini.Altered).should_be_true();
            };

            it["private method that takes in no parameters retains origin exception"] =
                expect<InvalidOperationException>(() => gemini.AlterException());

            it["private method that takes in dynamic parameter is publically accessible"] = () =>
            {
                gemini.SetAltered(true);

                ((bool)gemini.Altered).should_be_true();

                gemini.SetAltered(false);

                ((bool)gemini.Altered).should_be_false();
            };

            it["private method that takes in dynamic parameter retains exception"] =
                expect<InvalidOperationException>(() => gemini.SetAlteredException(true));

            it["private function that return enumerable of dynamic is publically accessible"] = () =>
                (gemini.Names() as IEnumerable<dynamic>).should_contain("name1");

            it["private function that takes a parameter and returns enumerable of dynamic is publically accessible"] = () =>
                (gemini.NamesWithPrefix("hi") as IEnumerable<dynamic>).should_contain("hiname1");

            it["private delegate (returning enumerable) that take in dynamic can interperet generic parameters"] = () =>
                (gemini.NamesWithArgs(prefix: "hi") as IEnumerable<dynamic>).should_contain("hiname1");

            it["private members can be redefined"] = () =>
            {
                (gemini.HelloString() as string).should_be("hello");

                gemini.HelloString = "booya";

                (gemini.HelloString as string).should_be("booya");
            };
        }
开发者ID:pragmaticlogic,项目名称:Oak,代码行数:60,代码来源:dynamic_methods_and_functions.cs


示例10: Service

        /// <summary>
        /// create a service class with an authorization token retrieved from GetAuthToken (if you have it). 
        /// If you do not provide one then you will only be able to get the URL to the 
        /// basecamp authorization requested page and to validate a code returned to you by that authorization.
        /// parameters come from the app you set up at integrate.37signals.com
        /// </summary>
        /// <param name="clientID">your client id from 37s</param>
        /// <param name="clientSecret">your client secret from 37s</param>
        /// <param name="redirectURI">the redirect URI you set up with 37s - this must match</param>
        /// <param name="appNameAndContact">your application name and contact info - added to your request header</param>
        /// <param name="cache">an optional cache to use for caching responses from 37s. if you don't provide one, it'll use the System.Runtime.Caching.MemoryCache.Default cache</param>
        /// <param name="accessToken">if you have an access token, provide it here. this is the entire json object returned from the call to GetAccessToken</param>
        public Service(string clientID,
            string clientSecret,
            string redirectURI,
            string appNameAndContact,
            BCXAPI.Providers.IResponseCache cache = null,
            dynamic accessToken = null)
        {
            if (cache == null)
            {
                _cache = new BCXAPI.Providers.DefaultMemoryCache();
            }
            else
            {
                _cache = cache;
            }

            _clientID = clientID;
            _clientSecret = clientSecret;
            _redirectURI = redirectURI;
            _appNameAndContact = appNameAndContact;
            _accessToken = accessToken;

            if (string.IsNullOrWhiteSpace(clientID) ||
                string.IsNullOrWhiteSpace(clientSecret) ||
                string.IsNullOrWhiteSpace(redirectURI) ||
               string.IsNullOrWhiteSpace(_appNameAndContact))
            {
                throw new Exceptions.BaseException("You must provide the client id, client secret, redirect uri, and your app name and contact information to use the API.");
            }
        }
开发者ID:WeAreMammoth,项目名称:bcxapi-dotnet,代码行数:42,代码来源:Service.cs


示例11: PostScheduleMessage

        public override void PostScheduleMessage(dynamic data)
        {
            try
            {

                oAuthTwitter OAuthTwt = new oAuthTwitter();
                TwitterAccountRepository fbaccrepo = new TwitterAccountRepository();
                TwitterAccount twtaccount = fbaccrepo.getUserInformation(data.UserId, data.ProfileId);


                OAuthTwt.CallBackUrl = System.Configuration.ConfigurationSettings.AppSettings["callbackurl"];
                OAuthTwt.ConsumerKey = System.Configuration.ConfigurationSettings.AppSettings["consumerKey"];
                OAuthTwt.ConsumerKeySecret = System.Configuration.ConfigurationSettings.AppSettings["consumerSecret"];
                OAuthTwt.AccessToken = twtaccount.OAuthToken;
                OAuthTwt.AccessTokenSecret = twtaccount.OAuthSecret;
                OAuthTwt.TwitterScreenName = twtaccount.TwitterScreenName;
                OAuthTwt.TwitterUserId = twtaccount.TwitterUserId;


                #region For Testing
                // For Testing 

                //OAuthTwt.ConsumerKey = "udiFfPxtCcwXWl05wTgx6w";
                //OAuthTwt.ConsumerKeySecret = "jutnq6N32Rb7cgbDSgfsrUVgRQKMbUB34yuvAfCqTI";
                //OAuthTwt.AccessToken = "1904022338-Ao9chvPouIU8ejE1HMG4yJsP3hOgEoXJoNRYUF7";
                //OAuthTwt.AccessTokenSecret = "Wj93a8csVFfaFS1MnHjbmbPD3V6DJbhEIf4lgSAefORZ5";
                //OAuthTwt.TwitterScreenName = "";
                //OAuthTwt.TwitterUserId = ""; 
                #endregion

                TwitterUser twtuser = new TwitterUser();

                if (string.IsNullOrEmpty(data.ShareMessage))
                {
                    data.ShareMessage = "There is no data in Share Message !";
                }

                JArray post = twtuser.Post_Status_Update(OAuthTwt, data.ShareMessage);

                
             
                Console.WriteLine("Message post on twitter for Id :" + twtaccount.TwitterUserId + " and Message: " + data.ShareMessage);
                ScheduledMessageRepository schrepo = new ScheduledMessageRepository();
                schrepo.updateMessage(data.Id);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Log log = new Log();
                log.CreatedDate = DateTime.Now;
                log.Exception = ex.Message;
                log.Id = Guid.NewGuid();
                log.ModuleName = "TwitterScheduler";
                log.ProfileId = data.ProfileId;
                log.Status = false;
                LogRepository logRepo = new LogRepository();
                logRepo.AddLog(log);
            }

        }
开发者ID:JBNavadiya,项目名称:socioboard,代码行数:60,代码来源:TwitterScheduler.cs


示例12: InitializationAuthVar

        public static void InitializationAuthVar(dynamic ViewBag, HttpSessionStateBase Session)
        {
            ViewBag.IsUser = false;
            ViewBag.IsModerator = false;
            ViewBag.IsAdmin = false;

            if (Session["user"] != null)
            {
                User user = (User)Session["user"];

                foreach (Role role in user.Roles)
                {
                    if (role.Name.Equals("USER_ROLE"))
                    {
                        ViewBag.IsUser = true;
                    }

                    if (role.Name.Equals("MODERATOR_ROLE"))
                    {
                        ViewBag.IsModerator = true;
                    }

                    if (role.Name.Equals("ADMIN_ROLE"))
                    {
                        ViewBag.IsAdmin = true;
                    }
                }


            }
        }
开发者ID:AlienaAngel,项目名称:TheatreSystem,代码行数:31,代码来源:AuthorizationHelper.cs


示例13: OnResponseReceived

		public override void OnResponseReceived( dynamic data ) {

			KCDatabase db = KCDatabase.Instance;

			//装備の追加 データが不十分のため、自力で構築しなければならない
			if ( (int)data.api_create_flag != 0 ) {
				var eq = new EquipmentData();
				eq.LoadFromResponse( APIName, data.api_slot_item );
				db.Equipments.Add( eq );
			}

			db.Material.LoadFromResponse( APIName, data.api_material );
			
			//logging
			if ( Utility.Configuration.Config.Log.ShowSpoiler ) {
				if ( (int)data.api_create_flag != 0 ) {

					int eqid = (int)data.api_slot_item.api_slotitem_id;

					Utility.Logger.Add( 2, string.Format( "{0}「{1}」の開発に成功しました。({2}/{3}/{4}/{5} 秘書艦: {6})",
						db.MasterEquipments[eqid].CategoryTypeInstance.Name, 
						db.MasterEquipments[eqid].Name,
						materials[0], materials[1], materials[2], materials[3],
						db.Fleet[1].MembersInstance[0].NameWithLevel ) );
				} else {
					Utility.Logger.Add( 2, string.Format( "開発に失敗しました。({0}/{1}/{2}/{3} 秘書艦: {4})",
						materials[0], materials[1], materials[2], materials[3],
						db.Fleet[1].MembersInstance[0].NameWithLevel ) );
				}
			}

			base.OnResponseReceived( (object) data );
		}
开发者ID:hirsaeki,项目名称:ElectronicObserver,代码行数:33,代码来源:createitem.cs


示例14: Process

        public WatchItem Process(dynamic value, string tag, bool showRawData = true)
        {
            if(value == null)
                return new WatchItem("null");

            return ProcessThing(value, tag, showRawData);
        }
开发者ID:jimmplan,项目名称:Dynamo,代码行数:7,代码来源:RevitWatchHandler.cs


示例15: FacebookUser

 public FacebookUser(dynamic me)
 {
     Name = me.name;
     Id = me.id;
     ImageUrl = me.picture.data.url;
     Installed = me.installed ?? false;
 }
开发者ID:bdennisco,项目名称:Shelf,代码行数:7,代码来源:FacebookUser.cs


示例16: DateTimeRelative

        public IHtmlString DateTimeRelative(dynamic Display, DateTime dateTimeUtc) {
            var time = _clock.UtcNow - dateTimeUtc;

            if (time.TotalDays > 7 || time.TotalDays < -7)
                return Display.DateTime(DateTimeUtc: dateTimeUtc, CustomFormat: T("'on' MMM d yyyy 'at' h:mm tt"));

            if (time.TotalHours > 24)
                return T.Plural("1 day ago", "{0} days ago", time.Days);
            if (time.TotalHours < -24)
                return T.Plural("in 1 day", "in {0} days", -time.Days);

            if (time.TotalMinutes > 60)
                return T.Plural("1 hour ago", "{0} hours ago", time.Hours);
            if (time.TotalMinutes < -60)
                return T.Plural("in 1 hour", "in {0} hours", -time.Hours);

            if (time.TotalSeconds > 60)
                return T.Plural("1 minute ago", "{0} minutes ago", time.Minutes);
            if (time.TotalSeconds < -60)
                return T.Plural("in 1 minute", "in {0} minutes", -time.Minutes);

            if (time.TotalSeconds > 10)
                return T.Plural("1 second ago", "{0} seconds ago", time.Seconds); //aware that the singular won't be used
            if (time.TotalSeconds < -10)
                return T.Plural("in 1 second", "in {0} seconds", -time.Seconds);

            return time.TotalMilliseconds > 0
                       ? T("a moment ago")
                       : T("in a moment");
        }
开发者ID:jecofang01,项目名称:OrchardNoCMS,代码行数:30,代码来源:DateTimeShapes.cs


示例17: SourceBindingEndpoint

 public SourceBindingEndpoint(INotifyPropertyChanged source, Type propertyType, dynamic propertyGetter, Delegate propertySetter)
 {
     this.Source = source;
     this.PropertyType = propertyType;
     this.PropertyGetter = propertyGetter;
     this.PropertySetter = propertySetter;
 }
开发者ID:Scellow,项目名称:Perspex,代码行数:7,代码来源:SourceBindingEndpoint.cs


示例18: ThrowIfError

        public static void ThrowIfError(HttpResponseMessage response, dynamic json)
        {
            if (json == null) return;

            if (!JsonHelpers.ContainsProperty(json, Constants.ErrorProperty)) return;

            var error = json[Constants.ErrorProperty];
            if (string.IsNullOrWhiteSpace(error)) return;

            CexApiException exception;

            if (error == Constants.NonceMustBeIncremented)
            {
                exception = new CexNonceException(response, Constants.NonceMustBeIncremented);
            }
            else if (error == Constants.PermissionDenied)
            {
                exception = new CexPermissionDeniedException(response, Constants.PermissionDenied);
            }
            else if (error == Constants.InvalidApiKey)
            {
                exception = new CexInvalidApiKeyException(response, Constants.InvalidApiKey);
            }
            else
            {
                exception = new CexApiException(response, error);
            }

            throw exception;
        }
开发者ID:jordansjones,项目名称:Cex.io-Api-Client,代码行数:30,代码来源:ExceptionOracle.cs


示例19: IsJsonString

 public static bool IsJsonString(dynamic o)
 {
     return o is string ||
         o.GetType() == typeof(DateTime) ||
         o.GetType() == typeof(Char) ||
         o.GetType() == typeof(Guid);
 }
开发者ID:kujotx,项目名称:Oak,代码行数:7,代码来源:DynamicToJson.cs


示例20: StackConfig

        public StackConfig(dynamic config)
        {
            try
            {
                // load the config data.
                Name = string.IsNullOrEmpty(config.name) ? "CoiniumServ.com" : config.name;

                Nodes = new List<IStackNode>();

                if (config.nodes is NullExceptionPreventer)
                {
                    Valid = true;
                    return;
                }

                foreach (var entry in config.nodes)
                {
                    Nodes.Add(new StackNode(entry));
                }

                Valid = true;
            }
            catch (Exception e)
            {
                Valid = false;
                Log.Logger.ForContext<StackConfig>().Error(e, "Error loading stack configuration");
            }
        }
开发者ID:carloslozano,项目名称:CoiniumServ,代码行数:28,代码来源:StackConfig.cs



注:本文中的dynamic类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# eChartType类代码示例发布时间:2022-05-24
下一篇:
C# dxDel类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap