如何自动将新类实例添加到数组中?
示例:
internal class AuthenticationHelper
{
/// <summary>
/// Async task to acquire token for Application.
/// </summary>
/// <returns>Async Token for application.</returns>
public static async Task<string> AcquireTokenAsync()
{
string clientId = ConfigurationManager.AppSettings["ida:ClientID"];
string appKey = ConfigurationManager.AppSettings["ida:AppKey"];
string graphResourceID = Constants.ResourceUrl;
string signedInUserID = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
// get a token for the Graph without triggering any user interaction (from the cache, via multi-resource refresh token, etc)
ClientCredential clientcred = new ClientCredential(clientId, appKey);
// initialize AuthenticationContext with the token cache of the currently signed in user, as kept in the app's EF DB
AuthenticationContext authContext = new AuthenticationContext(string.Format("https://login.microsoftonline.com/{0}", tenantID), new EFADALTokenCache(signedInUserID));
AuthenticationResult result = await authContext.AcquireTokenSilentAsync(graphResourceID, clientcred, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
return result.AccessToken;
}
/// <summary>
/// Get Active Directory Client for Application.
/// </summary>
/// <returns>ActiveDirectoryClient for Application.</returns>
public static ActiveDirectoryClient GetActiveDirectoryClient()
{
string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
Uri baseServiceUri = new Uri(Constants.ResourceUrl);
ActiveDirectoryClient activeDirectoryClient =
new ActiveDirectoryClient(new Uri(baseServiceUri, tenantID),
async () => await AcquireTokenAsync());
return activeDirectoryClient;
}
}
如何将Product类的新实例添加到products数组?我怎样才能附加到数组?
我尝试了一些代码,但我不知道如何在自己的课程中引用该课程。
我试过这样的事情:
class Product {
var name: String?
}
var products = [Product]()
谢谢!
答案 0 :(得分:3)
如果您希望新创建的对象存储在products
数组中,则需要将其声明为static
属性,以便所有实例共享它,否则它只会为您的每个实例添加第一个对象
class Product {
var name: String?
static var products = [Product]()
init() {
Product.products.append(self)
}
init(name: String) {
self.name = name
Product.products.append(self)
}
}
现在使用products
使用此Product.products
数组。
_ = Product(name: "One")
_ = Product(name: "two")
print(Product.products)
答案 1 :(得分:1)
您是否尝试过products.append(self)
?
答案 2 :(得分:1)
我不知道你为什么需要它,但你可以使用
class Product {
static var products: [Product] = []
var name: String?
init() {
products.append(self)
}
}