protected function extractAddress()
{
if (!$this->getRequest()->getPost('create_address')) {
return null;
}
$addressForm = $this->formFactory->create('customer_address', 'customer_register_address');
$allowedAttributes = $addressForm->getAllowedAttributes();
$addressData = [];
$regionDataObject = $this->regionDataFactory->create();
foreach ($allowedAttributes as $attribute) {
$attributeCode = $attribute->getAttributeCode();
$value = $this->getRequest()->getParam($attributeCode);
if ($value === null) {
continue;
}
switch ($attributeCode) {
case 'region_id':
$regionDataObject->setRegionId($value);
break;
case 'region':
$regionDataObject->setRegion($value);
break;
default:
$addressData[$attributeCode] = $value;
}
}
$arr = [];
$arr[] = $addressData;
$arr[] = $addressData;
for($i=0;$i<2;$i++){
$addressDataObject = $this->addressDataFactory->create();
$this->dataObjectHelper->populateWithArray(
$addressDataObject,
$arr[$i],
\Magento\Customer\Api\Data\AddressInterface::class
);
$addressDataObject->setRegion($regionDataObject);
if ($i==0){
$addressDataObject->setIsDefaultBilling(
$this->getRequest()->getParam('default_billing', false)
);
} else {
$addressDataObject->setIsDefaultShipping(
$this->getRequest()->getParam('default_shipping', false)
);
}
}
return $addressDataObject;
}
public function execute()
{
$resultRedirect = $this->resultRedirectFactory->create();
$this->session->regenerateId();
try {
$address = $this->extractAddress();
$addresses = $address === null ? [] : [$address];
$customer = $this->customerExtractor->extract('customer_account_create', $this->_request);
$customer->setAddresses($addresses);
}
}
//这里T是一个Enum类型的long值,PermissionBitMask是Enum的long值,而operation是一个整数值。
T bitmask = (T)PermissionBitMask;
bool hasAccess = (bitmask & (T)operation) == (T)operation;
答案 0 :(得分:2)
您可以将Enum.ToObject()方法用作:
private static T IntegerToEnum<T>(int i)
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("...");
}
return (T)Enum.ToObject(typeof(T), i);
}
和
private static T LongToEnum<T>(long i)
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("...");
}
return (T)Enum.ToObject(typeof(T), i);
}
答案 1 :(得分:2)
考虑枚举是可转换的,您可以在method/function?
上约束IConvertible
:
T
如果您可以使用C#7.3,那么public bool HasAccess<T>(T permissionBitMask, long operation) where T: IConvertible
{
long bitmask = permissionBitMask.ToInt64(null);
return (bitmask & operation) == operation;
}
也会受到限制。