假设我有一个Article模型,该模型具有一个字段,其中字段的名称用不同的语言表示:
class Article {
constructor(public name: Translation[]) { }
}
class Translation {
constructor(
public language: string,
public text: string
) { }
}
我希望能够调用一种方法,以将该文章名称转换为作为参数提供的语言:
article.name.translate('EN')
如何将这种方法添加到翻译的数组中?
答案 0 :(得分:3)
V1:
public static void main(String args[]) {
String stringToEncrypt = "plain_text";
String publicKey = "<public_key>";
System.out.println(encrypt(stringToEncrypt, publicKey))
}
public String encrypt(String plain, String publicKey) {
try {
byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT);
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
PublicKey rsaPublicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, rsaPublicKey);
byte[] plainTextBytes = plain.getBytes(Charset.forName("US-ASCII"));
byte[] encryptedBytes = cipher.doFinal(plainTextBytes);
return Base64.encodeToString(encryptedBytes, Base64.NO_WRAP));
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
V2:
class Article {
constructor(public name: Translation[]) { }
public translate(language:string):string {
return this.name.find(t=>t.language==language).text;
}
}
class Translation {
constructor(
public language: string,
public text: string
) { }
}
let a = new Article([
new Translation('EN', 'Yes'),
new Translation('DE', 'Ja')
]);
a.translate('EN');
答案 1 :(得分:0)
在运行时只有一个Array
类,因此为一种类型的数组添加方法将为所有类型的数组添加方法,这可能导致冲突。话虽如此,您只能为一种Typescript数组类型添加方法,例如
class Article {
constructor(public name: Translation[]) { }
}
class Translation {
constructor(
public language: string,
public text: string
) { }
}
interface Array<T> { // this has to be in global of în a module
translate(this: Translation[], lang: string): string;
}
Array.prototype.translate = function (lang) {
var t = this.find(o => o.language == lang);
return t && t.text;
}
let article = new Article([
]);
article.name.translate('EN')