首页 \ 问答 \ 如何在Swift中声明一个类级别的功能?(How do I declare a class level function in Swift?)

如何在Swift中声明一个类级别的功能?(How do I declare a class level function in Swift?)

我似乎无法在文档中找到它,我想知道它是否存在于本机Swift中。 例如,我可以在NSTimer上调用类级别的函数:

NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "someSelector:", userInfo: "someData", repeats: true)

但是我似乎找不到一个方法来做我的自定义对象,所以我可以称之为:

MyCustomObject.someClassLevelFunction("someArg")

现在,我知道我们可以混合使用Objective-C w / Swift, NSTimer类的方法可能是互操作性的残余。

  1. 在Swift中是否存在类级别的功能?

  2. 如果是,如何在Swift中定义一个类级别的函数?


I can't seem to find it in the docs, and I'm wondering if it exists in native Swift. For example, I can call a class level function on an NSTimer like so:

NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: "someSelector:", userInfo: "someData", repeats: true)

But I can't seem to find a way to do it with my custom objects so that I could call it like:

MyCustomObject.someClassLevelFunction("someArg")

Now, I know we can mix Objective-C w/ Swift and it's possible that the NSTimer class method is a remnant from that interoperability.

Question

  1. Do class level functions exist in Swift?

  2. If yes, how do I define a class level function in Swift?


原文:https://stackoverflow.com/questions/24008011
更新时间:2024-01-24 16:01

最满意答案

当将动态传递给CreateCommand ,编译器将其返回类型视为必须在运行时解析的动态。 不幸的是,你在这个解析器和C#语言之间碰到一些怪异的东西。 幸运的是,通过删除使用var强制编译器执行所期望的操作很容易解决:

public static dynamic DynamicWeirdness() {
    dynamic ex = new ExpandoObject ();
    ex.Query = "SELECT * FROM Products";
    using (var conn = OpenConnection()) {
        DbCommand cmd = CreateCommand(ex); // <-- DON'T USE VAR
        cmd.Connection = conn;
    }
    Console.WriteLine("It worked!");
    Console.Read();
    return null;
}

这已经在Mono 2.10.5上进行了测试,但我确信它与MS一起使用。


When you pass the dynamic to CreateCommand, the compiler is treating its return type as a dynamic that it has to resolve at runtime. Unfortunately, you're hitting some oddities between that resolver and the C# language. Fortunately, it's easy to work around by removing your use of var forcing the compiler to do what you expect:

public static dynamic DynamicWeirdness() {
    dynamic ex = new ExpandoObject ();
    ex.Query = "SELECT * FROM Products";
    using (var conn = OpenConnection()) {
        DbCommand cmd = CreateCommand(ex); // <-- DON'T USE VAR
        cmd.Connection = conn;
    }
    Console.WriteLine("It worked!");
    Console.Read();
    return null;
}

This has been tested on Mono 2.10.5, but I'm sure it works with MS too.

相关问答

更多
  • 使用ExpandoObject时,您可能看起来可以在运行时添加属性,它实际上不会在CLR级别执行此操作。 这就是为什么使用反射来获取在运行时添加的属性将无法正常工作的原因。 将ExpandoObject视为将字符串映射到对象的字典会有所帮助。 将ExpandoObject视为dynamic变量时,属性的任何调用都将路由到该字典。 dynamic exp = new ExpandoObject(); exp.A = "123"; 实际调用非常复杂并且涉及DLR,但其效果与写入相同 ((IDictionary ...
  • 您需要将ExpandoObject为dynamic : xdoc.Descendants("database") .Select(dbDetail => { dynamic expandoObj = new ExpandoObject(); expandoObj.DBDetailId = Convert.ToInt32(db ...
  • 当将动态传递给CreateCommand ,编译器将其返回类型视为必须在运行时解析的动态。 不幸的是,你在这个解析器和C#语言之间碰到一些怪异的东西。 幸运的是,通过删除使用var强制编译器执行所期望的操作很容易解决: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject (); ex.Query = "SELECT * FROM Products"; using (var conn = O ...
  • 我做错了,还是下列代码真的不可能? 真的不可能 赋值运算符左侧的事物必须是编译时已知的一个或多个字段,显然对于expando对象并不是这样。 为什么C#团队选择不允许与常规对象,匿名对象和枚举/列表相同的初始化语法? 你用短语表达逻辑错误的方式。 功能默认没有实现,然后我们围绕着几乎所有的功能,因为我们认为这是一个坏主意! 功能默认情况下未实现 ,必须执行才能正常工作。 实施任何功能的第一步是有人必须首先考虑它。 据我所知,我们从未做过。 特别是,2006年设计对象初始化器的人来说,相当困难的是,在2010 ...
  • 既然我写了你所指的MSDN文章,我想我必须回答这个。 首先,我预计这个问题,这就是为什么我写了一篇博客文章,展示了一个或多或少的ExpandoObject的真正用例: C#4.0中的Dynamic:ExpandoObject简介 。 很快,ExpandoObject可以帮助您创建复杂的层次对象。 例如,假设您在字典中有字典: Dictionary dict = new Dictionary(); Dictionary
  • 这个最简单的答案是不要自己重新发明。 只需使用Dapper,它就会提供这些扩展并处理参数以及将结果读者映射到您的类。 This most simple answer is to not reinvent this yourself. Just use Dapper it provides these kinds of extensions and deals with arguments plus mapping of the resulting reader to your classes.
  • 您的建议是正确的,您将能够使用点表示法查询动态对象的集合。 var ids = generatedItems.Cast().Select(x => x.Id); 但是,请记住,这里没有类型安全性,正如您所说,IntelliSense没有用,因为您使用的是动态对象。 如果您的代码取决于其中一个对象是否具有可选属性(例如,某些对象具有“标题”,而其他对象没有),则需要更多的手工劳动。 if((generatedItems as IDictionary).Con ...
  • 作为静态打字的忠实信徒, 这就是说,它看起来像ExpandoObject实现了IDictionary : dynamic foo1d = new ExpandoObject(); foo1d.a = "test"; dynamic foo2d = new ExpandoObject(); foreach (var kvp in (IDictionary)foo1d) { ((IDictionary)fo ...
  • 在Silverlight 5中,他们没有添加绑定到动态对象的默认机制,而是添加了一个新的接口ICustomTypeProvider 。 并且该接口也没有添加到ExpandoObject,但是使用expando,您应该能够使用索引器绑定,因为它是一个实现INotifyPropertyChanged的IDictionary In Silverlight 5 they didn't add a defau ...
  • 您不会在ExpandoObject上获取动态定义的方法的任何MethodInfo 。 动态定义的方法与动态定义的属性相同,它们恰好是委托类型。 但是,此委托类型包含一个名为Method的类型为MethodInfo的属性,您可以使用该属性: object ExecuteFunction(IDictionary obj, string name, params object[] parameters) { object pro ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)