简体   繁体   中英

How to use this public static method with dynamic?

I am seeing this that can be used to grab from a Web Service, but I'm not sure how to call it.

public static class IDSSExtensions
{
    public static T SetCredentials<T>(this T aServiceType)
    {        
        dynamic theDynamic = aServiceType;
        theDynamic.UserName = "Username";
        theDynamic.Password = "Password";
        return aServiceType = theDynamic;
    }
}

Something like this, I assume: IDSSExtensions.SetCredentials<>;

But, something needs to go inbetween the < and the > , but what? aServiceType ?

I have a WebReference with a namespace of: ServiceMembersIDSS, but that won't work and gives error if I put that in there. What goes in there?

For Example, can it be used like this:

Instead of this:

private AuthorizeHeader IDSSCredentials()
{
    ServiceMemberIDSS.AuthorizeHeader _authHeader = new ServiceMemberIDSS.AuthorizeHeader();
    _authHeader.UserName = "Username";
    _authHeader.Password = "Password";
    return _authHeader;
}

I can do this:

private AuthorizeHeader IDSSCredentials()
{
    ServiceMemberIDSS.AuthorizeHeader _authHeader = new ServiceMemberIDSS.AuthorizeHeader();
    _authHeader.SetCredentials();
    return _authHeader;
}

Is that correct?

This is a very odd chunk of code, but here goes:

T here is generic for any type of object. The "this" syntax in a static class and method makes this an extension method. Since this is an extension method of T with no constraints, including this file will add this method to all of your Objects. So you can technically call this method on any object like this:

Object foo = new Object();
foo.SetCredentials();

However the dynamic cast then assumes your object has two properties, UserName and Password. If the object doesn't have these properties, then it will throw an exception. Instead of T, the method should really take an interface that has the properties UserName and Password. Of course, you could call the method without an exception by simply creating your own object that has the properties UserName and Password.

public class MyObject
{
    public String UserName { get; set; }
    public String Password { get; set; }
}

MyObject myObject = new MyObject();
myObject.SetCredentials();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM