精华内容
下载资源
问答
  • How to Use Attributes in C#

    2019-10-05 04:38:57
    How to Use Attributes in C# Introduction Usinng an attribute is a way to add special meaning to our method and cause it to act in ...

    Introduction

    Usinng an attribute is a way to add special meaning to our method and cause it to act in a certain way. Before this was available, developers didn't have a way to define their own attributes. DotNet paved the way for developers and opened new horizons to conquer. Attributes are like adding behaviours to methods, classes, properties structures, events, modules, and so forth. It means we can enforce certain constraints on those methods, classes, properties and vice-versa to behave in the way specify to them.


    (continued)


    One more added feature is that, before DotNet, if we made a class or DLL and a newer version came along, the older version that should be removed or should not be used still exists. This causes a problem called DLL Hell. DotNet solved this problem by the concept of versioning. This means that the same DLL with the same name, containing some new methods with older methods can co-exist with a different version number.

    Let us start to learn to use attributes in C# code:

    Case 1

    I had a method in my old DLL. Now, I have updated my DLL and added two new methods and one new method that is the upgraded version of previous DLL.

    What should happen is that my previous programs that use this DLL should work properly. Or, if I intend to use the old method in the new program, it should tell me that the old method is obsolete and I should use the new method.

    Before DotNet, this wasn't possible. DotNet has removed this hurdle from the path of developers. Let us see how can we do this stuff:

    Using System;
    Namespace MyExample
    {
    Class MyAttribute
    {
    [Obsolete()]
    public static void SaySomething(string str)
    {
    Console.WriteLine(str);
    }
    public static void Talk(string str)
    {
    Console.WriteLine(str);
    }

    static void Main()
    {
    SaySomething("Hello to Sufyan");
    Console.ReadLine();
    }
    }
    }

    Here, when we call SaySomething("Hello to Sufyan"), it will execute the code but in the output window a warning message will be displayed, showing us that the SaySomething method is obsolete.

    Still, it doesn't ask us to use the new talk method SaySomething instead. To display a customized message, we will customize the obsolete attribute like this:

    [Obsolete("SaySomething() method is now Obsolete.
    Please use Talk()")]

    By using this approach, we can add additional meaning to our attribute.

    Note: We can have multiple attribute statements before a method or class. In such cases, if one of the statements is true, it will allow access to that particular method.

    There are many attributes that come with DotNet.

    • Conditional
    • DllImport
    • Obsolete
    • Serializable

    Conditional attribute

    By using the Conditional attribute, we are following a scenario that if a particular condition is true, the user will have access to that specific method. Suppose you wanted your specific method to run only if Internet Explorer is found on the system. Applying this type of security on a method was not easy in the past. Now, it is possible by applying conditional attributes.

    Case 2

    Suppose you want a method to run if program is in Debug mode. We will write the conditional statement as follows:

    [Conditional(.DEBUG.)]
    public static void Help(String str)
    {
    Console.WriteLine(str);
    }

    If one calls this method in Main(), it will run only if the program is in Debug mode. If you turn it off in the release mode, it will not run.

    DLL Import

    Before DotNet, if one wanted to access the core Windows API, he could add a reference and use the library provided by Windows SDK. In DotNet, if we want to access those core features of DotNet, we use DllImport. Component DLLs aren't accessed this way. They are accessed by making a reference to them. Normal DLLs are accessed by using the DllImport attribute.

    Case 3

    using System;
    System.Runtime.InteropServices;
    class Beeper
    {
    [DllImport(.kernel32.dll.)]
    Public static extern bool Beep(int frequency,int duration);
    static void Main()
    {
    Beep(1000,111);
    }
    }

    So far, we have learned how to use attributes in DotNet. Still, we haven't learn how to create our own custom attributes with specified behaviour that we assign.

    Steps in Creating a Custom Attribute

    1. Define the attribute's usage.
    2. Extend our class with AttributeClass.
    3. Define the behaviours to the class.

    Attribute behaviours can be of these types:

    • All—Any application element
    • Assembly—Attribute can be applied to an assembly
    • Class—Attribute can be applied to a class
    • Constructor—Attribute can be applied to a constructor
    • Delegate—Attribute can be applied to a delegate
    • Enum—Attribute can be applied to an enumeration
    • Event—Attribute can be applied to an event
    • Field—Attribute can be applied to a field
    • Interface—Attribute can be applied to an interface
    • Method—Attribute can be applied to a method
    • Module—Attribute can be applied to a module
    • Parameter—Attribute can be applied to a parameter
    • Property—Attribute can be applied to a property
    • ReturnValue—Attribute can be applied to a return value
    • Struct—Attribute can be applied to a structure

    The second step is to extend the class with the Attribute class. Basically, our attribute is a class that defines the behaviours of our attribute. For example:

    ...
    public class MySpecialAttribute:Attribute
    {...

    A point to be noted here is that the name of Attribute we are going to make is MySpecial. We didn't suffix the word Attribute after MySpecial. DotNet automatically suffixed it.

    Let us create a sample custom attribute that will execute the method if the regKey provided to the Attribute parameter is correct:

    using System;
    namespace RegKeyAttributeTestor
    {
    [AttributeUsage(AttributeTargets.Method|AttributeTargets.Struct,
    AllowMultiple=false,Inherited=false]
    public class MyAttribute:Attribute
    {
    private string regKey="a12nf";
    public MyAttribute(string regKey)
    {
    if(this.regKey==regKey)
    {
    Console.WriteLine("Permitted to use this App");
    }
    else
    {
    Console.WriteLine("Not registered to use this App");
    }
    }
    } //End Attribute class code
    class useAttrib
    {
    [MyAttribute("hello")]
    public static string SayHello(string str)
    {
    return str;
    }
    static void Main()
    {
    Console.WriteLine(SayHello("Hello to Sufyan"));
    Console.ReadLine();
    }
    }

    }
    AttributeUsage(AttributeTargets.Method|AttributeTargets.Struct,
    AllowMultiple=false, Inherited=false)]

    Here, multiple Attribute targets are declared by using "|" between different targets. Allows multiple=false means multiple attributes can be used with this attribute. Inherited=false shows that if some class extends a class that uses this attribute and calls a method that is bound to this attribute, that class has no access to this attribute unless this property is set to true.

    Reading Metadata from Assemblies

    We first write our custom attribute:

    using System;

    namespace Sufyan
    {
    [AttributeUsage(AttributeTargets.Method,AllowMultiple=false,
    Inherited=false)]
    public class RegKeyAttribute : Attribute
    {
    private string regKey;

    public RegKeyAttribute(string VRegKey)
    {
    this.regKey = VRegKey;
    if (this.regKey==.hello.)
    {
    Console.WriteLine("Aha! You're Registered");
    }
    else
    {
    Console.WriteLine("Oho! You're not Registered");
    }
    }
    }
    }

    Now, we shall write our code to reference it through Assembly;.

    Steps

    First, compile the first example as a Class library; it will generate a .dll file. We will place this .dll file in the bin folder of our second example we are going to make now.

    using System;
    using System.Reflection;
    using Sufyan;

    namespace AdvancedDotNet1
    {
    class Classic
    {
    static void Main(string[] args)
    {
    Assembly suf = Assembly.Load("RegKey");
    Type KIA=suf.GetType();
    []KO=Attribute.GetCustomAttributes(KIA);
    Object Regist =KO[0];
    Console.WriteLine("Registeration Code is :"+
    Regist.ToString() );
    Console.ReadLine();
    }
    }
    }

    System.Reflection is used to retrieve info from the assembly metadata.

    To use this in another class, verify that a specific method will execute if that particular developer is registered with me and I have issued him the license key to use.

    class useAttrib
    {
    [RegKeyAttribute ("hello")]
    public static string SayHello(string str)
    {
    return str;
    }
    static void Main()
    {
    Console.WriteLine(SayHello("Hello to Sufyan"));
    Console.ReadLine();
    }
    }

    Have a close look at this code. I have provided the Hello string as a parameter to the attribute. When we run this application, if we pass a string other then "hello", it will say that you are not registered. We can further modify it according to our need.

    posted on 2008-11-04 15:14  yongshi123 阅读( ...) 评论( ...) 编辑 收藏

    转载于:https://www.cnblogs.com/yongshi123/articles/1326381.html

    展开全文
  • //You can use whatever method you want to check the system version. UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle message:alertMessage delegate :nil cancelButtonTitle:...

    http://stackoverflow.com/questions/4463806/adding-a-simple-uialertview

    Adding a simple UIAlertView?

    答:
    When you want the alert to show, do this:

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"ROFL" 
                                                        message:@"Dee dee doo doo." 
                                                        delegate:self 
                                                        cancelButtonTitle:@"OK" 
                                                        otherButtonTitles:nil];
        [alert show];

    If you want to do something when the button is clicked, implement this delegate method:

    - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        // the user clicked OK
        if (buttonIndex == 0) {
            // do something here...
        }
    }

    And make sure your delegate conforms to UIAlertViewDelegate protocol:

    @interface YourViewController : UIViewController <UIAlertViewDelegate> 

    2

    Other answers already provide information for iOS 7 and older, however UIAlertView is deprecated in iOS 8.
    
    In iOS 8+ you should use UIAlertController. It is a replacement for both UIAlertView and UIActionSheet. Documentation: UIAlertController Class Reference. And a nice article on NSHipster.
    
    To create a simple Alert View you can do the following:
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title"
                                                                             message:@"Message"
                                                                      preferredStyle:UIAlertControllerStyleAlert];
    //We add buttons to the alert controller by creating UIAlertActions:
    UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"Ok"
                                                       style:UIAlertActionStyleDefault
                                                     handler:nil]; //You can use a block here to handle a press on this button
    [alertController addAction:actionOk];
    [self presentViewController:alertController animated:YES completion:nil];
    Swift:
    
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
    //We add buttons to the alert controller by creating UIAlertActions:
    let actionOk = UIAlertAction(title: "OK",
        style: .Default,
        handler: nil) //You can use a block here to handle a press on this button
    
    alertController.addAction(actionOk)
    
    self.presentViewController(alertController, animated: true, completion: nil)
    Note, that, since it was added in iOS 8, this code won't work on iOS 7 and older. So, sadly, for now we have to use version checks like so:
    
    NSString *alertTitle = @"Title";
    NSString *alertMessage = @"Message";
    NSString *alertOkButtonText = @"Ok";
    
    if ([MyOwnUtilsClass iOSMajorVersion] < 8) { //You can use whatever method you want to check the system version.
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
                                                            message:alertMessage
                                                           delegate:nil
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:alertOkButtonText, nil];
        [alertView show];
    }
    else {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:alertTitle
                                                                                 message:alertMessage
                                                                          preferredStyle:UIAlertControllerStyleAlert];
        //We add buttons to the alert controller by creating UIAlertActions:
        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:alertOkButtonText
                                                           style:UIAlertActionStyleDefault
                                                         handler:nil]; //You can use a block here to handle a press on this button
        [alertController addAction:actionOk];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    Swift 2:
    
    let alertTitle = "Title"
    let alertMessage = "Message"
    let alertOkButtonText = "Ok"
    
    if #available(iOS 8, *) {
        let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .Alert)
        //We add buttons to the alert controller by creating UIAlertActions:
        let actionOk = UIAlertAction(title: alertOkButtonText,
            style: .Default,
            handler: nil) //You can use a block here to handle a press on this button
    
        alertController.addAction(actionOk)
    }
    else {
        let alertView = UIAlertView(title: alertTitle, message: alertMessage, delegate: nil, cancelButtonTitle: nil, otherButtonTitles: alertOkButtonText)
        alertView.show()
    }
    展开全文
  • 参考 https://dzone.com/articles/interface-default-methods-java参考 https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.htmlJava 8 introduces “Default Method” or (Defender methods) ...

    参考 https://dzone.com/articles/interface-default-methods-java

    参考 https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

    Java 8 introduces “Default Method” or (Defender methods) new feature, which allows developer to add new methods to the interfaces without breaking the existing implementation of these interfaces. It provides flexibility to allow interface define implementation which will use as default in the situation where a concrete class fails to provide an implementation for that method.

    Let consider a small example to understand how it works:

    ?
    public interface oldInterface {
        public void existingMethod();
            default public void newDefaultMethod() {
            System.out.println("New default method"
                  " is added in interface");
        }
    }

    The following class will compile successfully in Java JDK 8,?

    public class oldInterfaceImpl implements oldInterface {
        public void existingMethod() {
            // existing implementation is here…
        }
    }

    If you create an instance of oldInterfaceImpl:?

    oldInterfaceImpl obj = new oldInterfaceImpl ();
    // print “New default method add in interface”
    obj.newDefaultMethod();

    In summary, Default methods enable to add new functionality to existing interfaces without breaking older implementation of these interfaces.

    When we extend an interface that contains a default method, we can perform following,

    • Not override the default method and will inherit the default method.
    • Override the default method similar to other methods we override in subclass..
    • Redeclare default method as abstract, which force subclass to override it.

    展开全文
  • While importing we detected an older version of numpy in ['D:\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\numpy']. One method of fixing this is to repeatedly uninstall numpy until none is ...

    Python3的numpy更新可能会出现问题!!

    这里的错误信息描述比较详细,
    但是也是希望可以对症下药,
    如果嫌麻烦可以直接跳到后文
    根据解决方案进行尝试。

    不说废话,直接看报错信息(Import Error):

    错误信息描述

    症状一

    ImportError: Something is wrong with the numpy installation.

    ImportError: Something is wrong with the numpy installation. 
    While importing we detected an older version of numpy in 
    ['D:\\Anaconda3\\envs\\tensorflow\\lib\\site-packages\\numpy']. 
    One method of fixing this is to repeatedly uninstall numpy 
    		until none is found, then reinstall this version.
    

    出现这个报错说明在你安装新的软件,或者更新numpy或者干什么的时候,旧的numpy没有卸载掉,两版numpy导致出现冲突。

    症状二

    一般这种情况下还会伴随有另一个报错:

    UserWarning: loaded more than 1 DLL from .libs
    

    进到信息中指定的.libs文件夹中会发现,确实是多了一个DLL文件,注意,这两个文件有一个你有权限删除,但是另一个你不能删除,因为python正在占用。

    报错信息more

    在前两个症状下进行下一步检测。
    如果在未采取措施时,您卸载python再重新安装,在python的语句中import numpy。您会看到这样的信息:(不想看的主儿往后翻,朕有翻译的)

    症状三

    >>> import numpy
    Traceback (most recent call last):
      File "D:\Python3.5.2\lib\site-packages\numpy\core\__init__.py", line 40, in <module>
        from . import multiarray
    ImportError: DLL load failed: 找不到指定的模块。
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "D:\Python3.5.2\lib\site-packages\numpy\__init__.py", line 142, in <module>
        from . import core
      File "D:\Python3.5.2\lib\site-packages\numpy\core\__init__.py", line 71, in <module>
        raise ImportError(msg)
    ImportError:
    IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!
    
    Importing the multiarray numpy extension module failed.  Most
    likely you are trying to import a failed build of numpy.
    Here is how to proceed:
    - If you're working with a numpy git repository, try `git clean -xdf`
      (removes all files not under version control) and rebuild numpy.
    - If you are simply trying to use the numpy version that you have installed:
      your installation is broken - please reinstall numpy.
    - If you have already reinstalled and that did not fix the problem, then:
      1. Check that you are using the Python you expect (you're using D:\Python3.5.2\python.exe),
         and that you have no directories in your PATH or PYTHONPATH that can
         interfere with the Python and numpy versions you're trying to use.
      2. If (1) looks fine, you can open a new issue at
         https://github.com/numpy/numpy/issues.  Please include details on:
         - how you installed Python
         - how you installed numpy
         - your operating system
         - whether or not you have multiple versions of Python installed
         - if you built from source, your compiler versions and ideally a build log
    
         Note: this error has many possible causes, so please don't comment on
         an existing issue about this - open a new one instead.
    

    翻译一下就是,“我给你3条路,第二条路说明你的numpy库破损,想知道怎么办就往后看。”。

    解决方案

    如报错信息所说

    • 先卸载numpy: pip uninstall numpy
    • 再卸载numpy,直到卸载到提示信息显示,此时完全已经没有numpy了为止
    • 下载numpy:pip install numpy
    • 此时应该可用;
      若不可用,查看python安装目录下的libs文件夹,删除掉其中的另一个dll文件,应该可用。

    若有效请点赞,以便更多学习者看到。

    展开全文
  • With older JDBC drivers for MySQL, you could always use a MySQL-specific method on the Statement interface, or issue the query SELECT LAST_INSERT_ID() after issuing an INSERT to a table that had an ...
  • Teaching Calculus with Infinitesimals

    千次阅读 2018-10-13 01:31:50
    using “indivisibles” (found, for example, in his The Method of Mechanical Theorems1) with extensions of Eudoxus’s method of exhaustion. Although Leibniz and Newton invented calculus by using infi...
  •  Java Native Method The goal for this chapter is to introduce you to Java's native methods. If you are new to Java, you may not know what native methods are, and even if you are an ...
  • How to use ASIHTTPRequest

    千次阅读 2013-10-30 15:45:18
    从ASIHTTPRequest官方文档copy下来的,收藏一下方便学习。 Creating and running requests ...The simplest way to use ASIHTTPRequest. Sending the startSynchronous message will execute the
  • OpenSSH implements all of the cryptographic algorithms needed for compatibility with standards-compliant SSH implementations, but since some of the older algorithms have been found to be weak, not a
  • If you need to track multiple queries and thus use different IDs for your Loaders, all you need to add is a simple case- or if-else-branch. onLoadFinished() This method is the most ...
  •  method creates a new Loader only if for this ID none has been created previously. Keep in mind that Android deals with configuration changes for you, thus a simple change in orientation is enough ...
  • Bind: Address Already in Use

    千次阅读 2014-03-18 10:41:23
    Bind: Address Already in Use Or How to Avoid this Error when Closing TCP Connections Normal Closure In order for a network connection to close, both ends have to send FIN (final) packets, which ind
  • -XX:CompileCommand=command,method[,option] -XX:CompileCommandFile=filename -XX:CompileOnly=methods -XX:CompileThreshold=invocations -XX:+DoEscapeAnalysis -XX:InitialCodeCacheSize=size ...
  • What Is a Native Method?

    2007-10-28 19:53:00
    What Is a Native Method?Simply put, a native method is the Java interface to non-Java code. It is Javas link to the "outside world." More specifically, a native method is a Java method whose imp
  • Java Native Method (本地方法)

    千次阅读 2008-12-11 16:06:00
    method modifier-much like you would use the public or static modifiers. Then, rather than supplying the method's body, you simply place a semicolon in its place. As an example, the following ...
  • advanced profiling的坑

    千次阅读 2018-02-05 17:41:54
    02-05 16:01:57.391 19883-19918/: errInfo:java.lang.ClassCastException: java.lang.ref.SoftReference cannot be cast to android.view.inputmethod.InputConnection at ...
  • To manage the capture from a device such as a camera or microphone, you assemble objects to represent inputs and outputs, and use an instance of AVCaptureSession to coordinate the data flow between ...
  • Which I/O Strategy Should I Use?

    千次阅读 2012-08-31 15:02:44
    There are several different conventions for communicating with Winsock, and each method has distinct advantages. The question of the hour is, what are these advantages, and how does
  • jQuery 中的 39 个技巧

    万次阅读 2016-12-17 10:27:09
    // You can use any jQuery method as a property! "width" : 200 , "height" : 50 } }); div.appendTo( '#result' ); 8.使用jQuery我们可以判断一个链接是否是外部的,并来添加一个icon在非外部链接...
  • use vim like a pro

    千次阅读 2015-03-06 23:07:21
    学习vim使用的一个很好的网址,在google上搜"use vim like a pro"就可以了。但是有的时候进不去,所以在这里备份一下~ Use Vim Like A Pro Why Bother? (reasons) There are many other editors, some being...
  • From: https://indico.io/blog/fast-method-stream-data-from-big-data-sources/ Maybe you’re training a machine learning model on a really big dataset. Perhaps you’ve got a big database dump and
  • If you want this code to work on older platforms or in browsers, the code will have to be transformed or “transpiled”. We can do this with a tool called  Babel . Install Babel ( babel-core ), the ...
  • Use of NFS Considered Harmful

    千次阅读 2010-09-16 09:23:00
    Use of NFS Considered Harmful
  • 【hive】How-to: Use a SerDe in Apache Hive

    千次阅读 2013-06-11 07:52:53
    转载:http://blog.cloudera.com/blog/2012/12/how-to-use-a-serde-in-apache-hive/ ...How-to: Use a SerDe in Apache Hive by Jon Natkins December 21, 2012 no comments Apache Hive is a
  • Android NDK编程: JNI技巧

    2018-12-11 21:37:52
    前言: 这篇文章是android官方文档... 有很多最佳实践, 比如储存classid/methodid, 管理线程, cpp和java线程交互, 异常UTF编码, 最后还有几个常见问题(UnsatisfiedLinkError错误, java和native分享数据). ...
  • Tech Tip: How to use initramfs. By: Rob Landley Last time, we covered why initramfs was created: because it saves memory, gives the user more control over the boot process, and simplifies the kern
  • Now the latest version of LINE is 6.6.1 and I want to use the same apk downgrade method to backup the database of LINE. Guess what? I could not install older version LINE apk, and the error messages ...
  • Decide on a Substitute Solution ...The most challenging task in using newer UI features in a backward-compatible way is deciding on and implementing an older (fallback) solution for older platform versi

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 12,511
精华内容 5,004
关键字:

methodolderuse